Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I am trying to deserialize the XML data but due to & it is getting exception but i need to insert xml with the same data.

Below is my sample xml data
string xml=@"
<customer>
<companyname>
Testing & Testing Pvtltd

<customer>";

I am using the below code



public static T Deserialize<T>(string xml)
    {
XmlSerializer ser =new XmlSerializer(typeof(T));
        T obj;
        using (MemoryStream memStream = new MemoryStream(new UTF8Encoding()).GetBytes(xml)))
        {
            
            obj = (T)ser.Deserialize(memStream);
        }
        return obj;
    }


What I have tried:

string xml=@"
<customer>
 <CompanyName>
    Testing & Testing Pvtltd
 </CompanyName>
<customer>";

I am using the below code



<pre>public static T Deserialize<T>(string xml)
    {
XmlSerializer ser =new XmlSerializer(typeof(T));
        T obj;
        using (MemoryStream memStream = new MemoryStream(new UTF8Encoding()).GetBytes(xml)))
        {
            
            obj = (T)ser.Deserialize(memStream);
        }
        return obj;
    }
Posted
Updated 30-Jun-21 22:50pm

& is a special character in XML, and cannot appear on its own.

To express a single & in XML, it needs to be encoded as &amp;.

You need to get whoever generated that file to fix their code, since what they are currently providing you with is not XML.
 
Share this answer
 
Your XML file is not a so-called well-formed one.
It should be like this
<customer>
    <companyname>Testing & Testing Pvtltd</companyname>
</customer>

Each beginning tag must have a corresponding ending tag.
e.g.
<MyData>...</MyData>
You can verify XML files online here: Validate XML files[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900