Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse only part of xml

Tags:

c#

.net

xml

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)?

like image 219
ispiro Avatar asked Dec 23 '13 16:12

ispiro


2 Answers

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();
}
like image 52
Paddy Avatar answered Sep 18 '22 22:09

Paddy


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.

like image 35
Jason Williams Avatar answered Sep 17 '22 22:09

Jason Williams