December 2007
Intermediate to advanced
896 pages
19h 57m
English
You need to read in all the elements of an XML document and obtain information about each element, such as its name and attributes.
Create an XmlReader and use its Read method to process the document as shown in Example 15-1.
Example 15-1. Reading an XML document
using System;
using System.Xml;
using System.Xml.Linq;
namespace CSharpRecipes
{
public class AccessXml
{
public static void AccessXml( )
{
// New LINQ to XML syntax for constructing XML
XDocument xDoc = new XDocument(
new XDeclaration("1.0", "UTF-8", "yes"),
new XComment("My sample XML"),
new XProcessingInstruction("myProcessingInstruction",
"value"),
new XElement("Root",
new XElement("Node1",
new XAttribute("nodeId", "1"), "FirstNode"),
new XElement("Node2",
new XAttribute("nodeId", "2"), "SecondNode"),
new XElement("Node3",
new XAttribute("nodeId", "1"), "ThirdNode")
)
);
// write out the XML to the console
Console.WriteLine(xDoc.ToString( ));
// create an XmlReader from the XDocument
XmlReader reader = xDoc.CreateReader( );
reader.Settings.CheckCharacters = true;
int level = 0;
while (reader.Read( ))
{
switch (reader.NodeType)
{
case XmlNodeType.CDATA:
Display(level, "CDATA: {0}", reader.Value);
break;
case XmlNodeType.Comment:
Display(level, "COMMENT: {0}", reader.Value);
break;
case XmlNodeType.DocumentType:
Display(level, "DOCTYPE: {0}={1}",
reader.Name, reader.Value);
break;
case XmlNodeType.Element:
Display(level, "ELEMENT: {0}", reader.Name); level++; ...Read now
Unlock full access