Accessing Text from Elements

When working with an XmlDocument and its child elements, you may need to retrieve text data from between the start and end tags of an element. Using the XmlTextReader, you can call ReadElementString or ReadString to get text with an element. With the XmlElement object you have two options, as well. The easiest way to get the text content of an element is to use the InnerText property, which returns the concatenated text values of the node and all its child nodes. For example, calling InnerText on the DocumentElement of an XmlDocument loaded with <root>first<child>,second</child>,last</root> will return the string first,second,last. This method can also be used to set the InnerText of the current node. It is very important to know that setting the InnerText property of a node will replace all of the node's children with the parsed content of the given string.

Listing 11.8 shows how to use the InnerText property to read the content of an XmlElement.

Listing 11.8.
C#
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Book>" +
            "<Title>Catcher in the Rye</Title>" +
            "<Price>25.98</Price>" +
            "</Book>");
MessageBox.Show("Price: " +
                doc.DocumentElement["Price"].InnerText);

VB
Dim doc As New XmlDocument()
doc.LoadXml("<Book>" & _
            "<Title>Catcher in the Rye</Title>" & +
            "<Price>25.98</Price>" & +
            "</Book>")
MessageBox.Show("Price: " & _
                doc.DocumentElement["Price"].InnerText)

The second way to access the text of an XmlElement is to retrieve the value of its child text nodes. If the element contains only string data and no markup, you can retrieve the Value property of the node's first child. Of course, if the element contains mixed content, you will have to either call the InnerText property or walk the child nodes or gather the text manually. Listing 11.9 illustrates using the FirstChild and Value properties to get the text values from a node.

Listing 11.9.
C#
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Book>" +
            "<Title>Catcher in the Rye</Title>" +
            "<Price>25.98</Price>" +
            "</Book>");

MessageBox.Show("Price: " +
                doc.DocumentElement["Price"].FirstChild.Value);

VB
Dim doc As New XmlDocument
doc.LoadXml("<Book>" & _
            "<Title>Catcher in the Rye</Title>" & _
            "<Price>25.98</Price>" & _
            "</Book>")

MessageBox.Show("Price: " &_
                doc.DocumentElement["Price"].FirstChild.Value)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.123.106