InnerText and InnerXml

To illustrate traversing an XmlDocument, we'll use the following XML file:

 

        <?xml version="1.0" encoding="utf-8" standalone="yes"?>
        <customer id="123" status="archived">
          <firstname>Jack</firstname>
          <lastname>Smith</lastname>
        </customer>

  

The InnerText property represents the concatenation of all child text nodes.

The following two lines both output Jim, since our XML document contains only a single text node:


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.IO;
class Program
{
    static void Main()
    {

        XmlDocument doc = new XmlDocument();
        doc.Load("customer.xml");


        Console.WriteLine(doc.DocumentElement.ChildNodes[0].InnerText);
        Console.WriteLine(doc.DocumentElement.ChildNodes[0].FirstChild.Value);
    }
}

The output:


Jack
Jack

Setting the InnerText property replaces all child nodes with a single text node.

Be careful when setting InnerText to not accidentally wipe over element nodes.

For example:


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.IO;
class Program
{
    static void Main()
    {

        XmlDocument doc = new XmlDocument();
        doc.Load("customer.xml");

        doc.DocumentElement.ChildNodes[0].FirstChild.InnerText = "NewValue";  
        

    }
}
java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.