Gary2Seven
asked on
reading XML document forward and back
I need to "seek" some nodes by name in an XML document, so I can retrieve the element value
XMLReader and XMLTextReader only read forward, since I don't know what order the nodes will be in within the XML I need to able to search forward and back or send the pointer back to the top so I can reissue a ReadToFollowing().
I don't want the overhead or opening and closing the reader every time, any ideas?
many thanks
Gary.
XMLReader and XMLTextReader only read forward, since I don't know what order the nodes will be in within the XML I need to able to search forward and back or send the pointer back to the top so I can reissue a ReadToFollowing().
I don't want the overhead or opening and closing the reader every time, any ideas?
many thanks
Gary.
For that kind of manipulation you wuold be better off loading into an XmlDocument and using XPath to query for nodes.
I agree with what carl said above. Load the xml document into the XmlDocument class and use XPathNavigator to navigate through the document. I use it ALL the time and love it.
Attached is a small example in C#:
Attached is a small example in C#:
//Import the "System.Xml" and "System.Xml.XPath" namespaces at the top of you're code.
public void ReadXml(string xmlFilePath)
{
//Load xml file and create navigator:
XmlReader reader = new XmlTextReader(xmlFilePath);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
reader.Close();
XPathNavigator nav = doc.CreateNavigator();
nav.MoveToRoot(); //Moves to the very beginning of the document (before any nodes)
nav.MoveToFirstChild(); //Moves to the first child node of root, which is your main xml node
//Then you can roll through chile nodes using loops like this:
do
{
if(nav.Name == "SomeXmlTagName")
{
string mystring = nav.InnerXml;
}
}(nav.MoveToNext());
}
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.