Search This Blog

Friday, December 9, 2011

How to parse XML if it has & symol in the element

Here i s my  xml

      <FieldName>Test special chars</FieldName>
      <FieldValue>~ ! # $ %  &  ( ) + =.test</FieldValue>
      <FieldValueLabel>~ ! # $ % &  ( ) + =.test</FieldValueLabel>

in fileldVale and Field lable tags  value has & symbol.
Actually we have  xml processor,    it will take xml through hTML post and parses the xml and save it into the database.
Till now that proceesor is working great. But today we got one post with above tag values.

Since it has &, we were not able to parse and save it into the database.
I search ed it in the google,  and found & and < are illegal characters for XML parser.
And according to some one suggestion I did like this.
      <FieldValue>~ ! # $ %  &amp;  ( ) + =.test</FieldValue>
      <FieldValueLabel>~ ! # $ % &amp;  ( ) + =.test</FieldValueLabel>

Still was getting an error.
Could some one please help me to solve this issue.
Thanks in adavance.
It is a production issue for us. Please some one suggest me.


If you are still getting the error try to replace "<" with "&lt;" and ">" with "&gt;"

or try this code

If i am correct then the areas where you are getting these (&) type of values call this method below and pass your value,this method will return the correct xml valid string.

    myxml= myxml+ EscapeXML("Das & Das");

        using System.Security;//Namespace add it on top of your class

        public string EscapeXML(string inputXml)
            string xml = inputXml;

            if (!string.IsNullOrEmpty(xml))
                 xml = SecurityElement.Escape(inputXml);

            return xml;



No comments:

Post a Comment