how to write >, <, &to XML file

Hello,
I try to write these characters to an XML file. but in the XML file it shows:
&gt; &lt; &amp; instead. how can i write correctly to the XML file or at least read correctly(assign the innertext to a variable)
here is my code for writing to XML file:
XmlElement title= xmldoc.CreateElement("Title");
title.InnerText = txtName.Text;
newBook.AppendChild(title);


Answer this question

how to write >, <, &to XML file

  • Roberto Venturelli

    //Well im still get &gt; & lt; and &amp back.//

    using System;

    using System.Xml;

     

    public class Test {

      public static void Main() {

        XmlDocument doc = new XmlDocument();

        XmlElement title = doc.CreateElement("Title");

        title.InnerText = "foo < bar > baz";

     

        Console.WriteLine("Display the InnerText of the element:");

        Console.WriteLine(title.InnerText);

      }

    }

     

    Output:

    Display the InnerText of the element:
    foo < bar > baz

    Note that you get special characters back without escaping.

     

    //the XML file also contains these formats instead of '<>&'.//

     

    This is expected. These characters are reserved for mark-up, and must be escaped if used not for mark-up. Please read the official XML spec available at http://www.w3.org/TR/REC-xml/ for more information.


  • Nick Y

    Well im still get &gt; & lt; and &amp back. the XML file also contains these formats instead of '<>&'. I don't quite understand

  • Chris Wu

    Anton, you're right. in the xml file it's formatted with &gt;... but innertext format the text. cool

  • Quazarman

    The characters '<>&" have special meaning in XML and must be escaped if used literally. The InnerText property returns the string value of the given node in unescaped form, exactly what you are looking for.
  • how to write >, <, &to XML file