Groups | Blog | Home
all groups > dotnet xml > october 2005 >

dotnet xml : Index of using XPATH?


Ken Getz
10/13/2005 9:40:39 AM
Hi. I have an xml file in this format:

<strings>
<string>Item1</string>
<string>Item2</string>
<string>Item3</string>
<string>Item4</string>
</string>

I'm looking for the best way to search for a specific string, and return the
index of its node within the strings element. That is, if someone enters
Item3, I need the value 3 (or 2, if the index is 0-based). I have a feeling
there's a reasonably simple XPath expression that will get this for me, but
I'm trying to avoid iterating through all the elements to find the index. I
might have several thousands, or tens of thousands, of items to look
through, so a linear search for a match would be ugly, especially if I could
use an XmlTextReader or some other technique that doesn't require me to load
the entire XML file first into an XmlDocument object.

I know how to do this the iterative way -- if you have a suggestion about
how to do this in some elegant way, using XPath, I'd love to hear it!
Thanks -- Ken

Ken Getz
10/13/2005 10:21:42 AM
Cool. Thanks. I appreciate the info. Got it working, using XPathNavigator.
If the file is large, however, I don't want to load the whole thing -- it
would be better to have a framework class stop loading once it found the
correct node. Do you (or anyone else) have suggestions on how to optimize
the lookup, with perhaps a simple code sample? Thanks. -- Ken

[quoted text, click to view]


Martin Honnen
10/13/2005 7:01:29 PM


[quoted text, click to view]

</strings>

[quoted text, click to view]

You can check the number of preceding siblings e.g.
/strings/string[. = 'Item3']/preceding-sibling::string
Of course XPath can count too
count(/strings/string[. = 'Item3']/preceding-sibling::string)

--

Martin Honnen --- MVP XML
Chris Lovett
10/14/2005 9:42:00 AM
XmlDocument is not a database system. As soon as you say you don't want to
load the whole thing you have two options:
1) Break the data into multiple XML files (but then understand there is no
XPath engine that can tie these back together - so you have ro manage which
file to load and query individually yourself).
2) use a real database system - like SQL Server 2005 (see
http://lab.msdn.microsoft.com/express/sql/).


[quoted text, click to view]

ken.getz NO[at]SPAM gmail.com
10/15/2005 2:03:32 PM
Hi. I appreciate the reply, but of course, I don't control the XML I'm
given to parse out. There ARE techniques that don't require loading the
entire XML file -- .NET provides the XmlTextReader, which reads it in
element by element. I just wasn't sure what the best solution was. --
Ken
AddThis Social Bookmark Button