Jump to content

XML/XPath: Difference between revisions

no edit summary
No edit summary
Line 85:
 
==[[C#]]==
XmlReader XReader;
 
// Either read the xml from a string ...
XReader = XmlReader.Create(new StringReader("<inventory title=... </inventory>"));
 
// ... or read it from the file system.
XReader = XmlReader.Create(new StringReader("<inventory title=... </inventory>"));
XReader = XmlReader.Create("xmlfile.xml");
 
// Create a XPathDocument object (which implements the IXPathNavigable interface)
// ... or read it from the file system.
// which is optimized for XPath operation. (very fast).
IXPathNavigable XDocument = new XPathDocument(XReader);
 
// Create a Navigator to navigate through the document.
XReader = XmlReader.Create("xmlfile.xml");
XPathNavigator Nav = XDocument.CreateNavigator();
 
Nav = Nav.SelectSingleNode("//item");
// Create a XPathDocument object (which implements the IXPathNavigable interface)
 
// Move to the first element of the selection. (if available).
// which is optimized for XPath operation. (very fast).
if(Nav.MoveToFirst())
Console.WriteLine(Nav.OuterXml); // The outer xml of the first item element.
 
// Get an iterator to loop over multiple selected nodes.
IXPathNavigable XDocument = new XPathDocument(XReader);
XPathNodeIterator Iterator = XDocument.CreateNavigator().Select("//price");
 
while (Iterator.MoveNext())
// Create a Navigator to navigate through the document.
NodesValues Console.AddWriteLine(Iterator.Current.Value);
XPathNavigator Nav = XDocument.CreateNavigator();
 
Iterator = XDocument.CreateNavigator().Select("//name");
Nav = Nav.SelectSingleNode("//item");
 
// Use a generic list.
// Move to the first element of the selection. (if available).
List<string> NodesValues = new List<string>();
if(Nav.MoveToFirst())
Console.WriteLine(Nav.OuterXml); // The outer xml of the first item element.
 
while (Iterator.MoveNext())
// Get an iterator to loop over multiple selected nodes.
NodesValues.Add(Iterator.Current.Value);
XPathNodeIterator Iterator = XDocument.CreateNavigator().Select("//price");
 
// Convert the generic list to an array and output the count of items.
while (Iterator.MoveNext())
Console.WriteLine(IteratorNodesValues.CurrentToArray().ValueLength);
 
Iterator = XDocument.CreateNavigator().Select("//name");
 
// Use a generic list.
List<string> NodesValues = new List<string>();
 
while (Iterator.MoveNext())
NodesValues.Add(Iterator.Current.Value);
 
// Convert the generic list to an array and output the count of items.
 
Console.WriteLine(NodesValues.ToArray().Length);
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.