Consider the following xml:
<?xml version="1.0" encoding="utf-8" ?>
<Outer>
<Inner1>ABC</Inner1>
<Inner2>DEF</Inner2>
</Outer>
I want to be able to get Inner1
's value ("ABC") without parsing the whole document. This is because in reality the document might be quite long. Is there a way to do this using .net (XDocument
. As opposed to manually parsing it)?
You can use XmlReader
, it doesn't parse the entire document, but provides forwards only access through a document (similar to the SAX parser):
http://msdn.microsoft.com/en-us/library/system.xml.xmlreader(v=vs.110).aspx
Something like the following, I think:
using (XmlReader reader = XmlReader.Create("sample.xml")) {
// Move the reader to the inner1 node
reader.MoveToContent();
reader.ReadToDescendant("Inner1");
return reader.ReadElementContentAsString();
}
You will need to parse everything up to the Data you want in order to find and extract it. However, if you use an XmlReader to do this you will be able to abort parsing as soon as you find what you need. Using XmlDocument in contrast, you must load the entire document before you can start searching within it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With