XML/XPath: Difference between revisions

Content added Content deleted
No edit summary
Line 89: Line 89:
// Either read the xml from a string ...
// Either read the xml from a string ...
XReader = XmlReader.Create(new StringReader("<inventory title=... </inventory>"));
XReader = XmlReader.Create(new StringReader("<inventory title=... </inventory>"));

// ... or read it from the file system.
// ... or read it from the file system.
XReader = XmlReader.Create("xmlfile.xml");
XReader = XmlReader.Create("xmlfile.xml");

// Create a XPathDocument object (which implements the IXPathNavigable interface)
// Create a XPathDocument object (which implements the IXPathNavigable interface)
// which is optimized for XPath operation. (very fast).
// which is optimized for XPath operation. (very fast).
IXPathNavigable XDocument = new XPathDocument(XReader);
IXPathNavigable XDocument = new XPathDocument(XReader);

// Create a Navigator to navigate through the document.
// Create a Navigator to navigate through the document.
XPathNavigator Nav = XDocument.CreateNavigator();
XPathNavigator Nav = XDocument.CreateNavigator();

Nav = Nav.SelectSingleNode("//item");
Nav = Nav.SelectSingleNode("//item");

// Move to the first element of the selection. (if available).
// Move to the first element of the selection. (if available).
if(Nav.MoveToFirst())
if(Nav.MoveToFirst())
Console.WriteLine(Nav.OuterXml); // The outer xml of the first item element.
Console.WriteLine(Nav.OuterXml); // The outer xml of the first item element.

// Get an iterator to loop over multiple selected nodes.
// Get an iterator to loop over multiple selected nodes.
XPathNodeIterator Iterator = XDocument.CreateNavigator().Select("//price");
XPathNodeIterator Iterator = XDocument.CreateNavigator().Select("//price");

while (Iterator.MoveNext())
while (Iterator.MoveNext())
Console.WriteLine(Iterator.Current.Value);
Console.WriteLine(Iterator.Current.Value);

Iterator = XDocument.CreateNavigator().Select("//name");
Iterator = XDocument.CreateNavigator().Select("//name");

// Use a generic list.
// Use a generic list.
List<string> NodesValues = new List<string>();
List<string> NodesValues = new List<string>();

while (Iterator.MoveNext())
while (Iterator.MoveNext())
NodesValues.Add(Iterator.Current.Value);
NodesValues.Add(Iterator.Current.Value);

// Convert the generic list to an array and output the count of items.
// Convert the generic list to an array and output the count of items.
Console.WriteLine(NodesValues.ToArray().Length);
Console.WriteLine(NodesValues.ToArray().Length);