Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>My experience of <code>XmlReader</code> is that it's very easy to accidentally read too much. I know you've said you want to read it as quickly as possible, but have you <em>tried</em> using a DOM model instead? I've found that LINQ to XML makes XML work much <em>much</em> easier.</p> <p>If your document is particularly huge, you can combine <code>XmlReader</code> and LINQ to XML by creating an <code>XElement</code> from an <code>XmlReader</code> for each of your "outer" elements in a streaming manner: this lets you do most of the conversion work in LINQ to XML, but still only need a small portion of the document in memory at any one time. Here's some sample code (adapted slightly from <a href="http://blogs.msdn.com/xmlteam/archive/2007/03/24/streaming-with-linq-to-xml-part-2.aspx" rel="noreferrer">this blog post</a>):</p> <pre><code>static IEnumerable&lt;XElement&gt; SimpleStreamAxis(string inputUrl, string elementName) { using (XmlReader reader = XmlReader.Create(inputUrl)) { reader.MoveToContent(); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name == elementName) { XElement el = XNode.ReadFrom(reader) as XElement; if (el != null) { yield return el; } } } } } } </code></pre> <p>I've used this to convert the StackOverflow user data (which is enormous) into another format before - it works very well.</p> <p>EDIT from radarbob, reformatted by Jon - although it's not quite clear which "read too far" problem is being referred to...</p> <p>This should simplify the nesting and take care of the "a read too far" problem.</p> <pre><code>using (XmlReader reader = XmlReader.Create(inputUrl)) { reader.ReadStartElement("theRootElement"); while (reader.Name == "TheNodeIWant") { XElement el = (XElement) XNode.ReadFrom(reader); } reader.ReadEndElement(); } </code></pre> <p>This takes care of "a read too far" problem because it implements the classic while loop pattern:</p> <pre><code>initial read; (while "we're not at the end") { do stuff; read; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload