You must Sign In to post a response.
  • Category: ASP.NET

    How to escape Special character in XML

    Hi All,

    I have XML data in string and tried to convert that string in to XML using
    XmlDocument xl=new XmlDocument();

    It was not parsing because my string has special character in xml element like below.

    <DATA>name < lastname</DATA>
    <DATA>Myname > lastname</DATA>
    <DATA>some special character in between text</DATA>
    There were many <DATA> in my xml. It was generating dynamically.

    I have tried to change < < > > but it was replacing other XML tags.

    How to escape above special character without change other XML tags ?

    Please help me to resolve this
  • #763413
    Hello Rajan,

    You can use this code :

    VB :

    Private Function ReplaceXmlText(ByVal strXmlText As String) As String
    Dim strXml As String
    strXml = Replace(strXmlText, "&", "&")
    strXml = Replace(strXml, "'", "'")
    strXml = Replace(strXml, """", """)
    strXml = Replace(strXml, ">", ">")
    strXml = Replace(strXml, "<", "<")
    ReplaceXmlText = strXml
    End Function

    Example :

    <DATA>" + ReplaceXmlText(">") + "</DATA>

    C# :

    private string ReplaceXmlText(string strXmlText)
    string strXml = null;
    strXml = Strings.Replace(strXmlText, "&", "&");
    strXml = Strings.Replace(strXml, "'", "'");
    strXml = Strings.Replace(strXml, "\"", """);
    strXml = Strings.Replace(strXml, ">", ">");
    strXml = Strings.Replace(strXml, "<", "<");
    return strXml;

    Example :
    <DATA>" + ReplaceXmlText("<") + "</DATA>

    Hope this will be helpful for you.

    Nirav Lalan
    DNS Gold Member
    "Failure is the path of least persistence"

  • #763414
    you can use the following for escape for you xml

    < is replaced with <
    > is replaced with >

    By Nathan
    Direction is important than speed

  • #763530
    Have you tried to use .Save() method of XMLDocument class, after using 'loadXml()' method
    but before that be sure to keep at least one root element
    see below snippet
    string szData = "<root><data>Appple<data><data>Mango<data></root>";
    XmlDocument xl=new XmlDocument();

    hope it helps

    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]

Sign In to post your comments