title: how to get stream positions of xml elements in .NET
body: <p>How can I get the stream position of an XElement in .NET 4 in a reasonably efficient way?</p>
  
  <pre><code>          1         2         3         4         5         6         7         8
  01234567890123456789012345678901234567890123456789012345678901234567890123456789012
  &lt;root&gt;&lt;group id="0" combiner="or"&gt;&lt;filter id="1" /&gt;&lt;filter id="2" /&gt;&lt;/group&gt;&lt;/root&gt;
  </code></pre>
  
  <p>I want to create from the above a map to segments</p>
  
  <pre><code>{ { "/root",                  Segment(0 , 82) },
    { "/root/group-0",          Segment(6 , 75) },
    { "/root/group-0/filter-1", Segment(34, 50) },
    { "/root/group-0/filter-2", Segment(51, 67) } }
  </code></pre>
  
  <p><strong>Notes</strong></p>
  
  <ul>
  <li>second fields of segments can be lengths instead of end indices</li>
  <li>methods can be more general/extended to other byte representations</li>
  </ul>
  
  <p><strong>Blog Post About My Answer with Memory Profiling Screenshots</strong></p>
  
  <p><a href="http://corsis.posterous.com/xml-keyvalue-cache-optimizations" rel="nofollow noreferrer">http://corsis.posterous.com/xml-keyvalue-cache-optimizations</a></p>
  
  <p><strong>Bonus</strong></p>
  
  <ul>
  <li><strong>use a form of compression</strong> that allows <strong>O(1) access</strong> to elements <strong>but</strong> requires <strong>only a single copy of the whole document</strong> without any subelements duplicated in the memory.</li>
  </ul>
  
  <p><strong>Bonus Example</strong></p>
  
  <pre><code>store["/root"].Decompress()         **O(1)**
  store["/root/group-0"].Decompress() **O(1)**
  </code></pre>