Query within an XML document
I have an XML document in my asp.net application
containing country information
eg
<Country>
<CNo>1</CNo>
<Country>Afghanistan</Country>
<Nationality>Afghan</Nationality>
<ISDCode>93</ISDCode>
<Continent>Asia</Continent>
</Country>
<Country>
<CNo>2</CNo>
<Country>Albania</Country>
<Nationality>Albanian</Nationality>
<ISDCode>355</ISDCode>
<Continent>Europe</Continent>
</Country>
<Country>
<CNo>3</CNo>
<Country>Algeria</Country>
<Nationality>Algerian</Nationality>
<ISDCode>213</ISDCode>
<Continent>Africa</Continent>
</Country>
When a country is selected from a dropdown list, I want to be able to run
through the xml document and pick out the corresponding continent only. What is
the best way to do this?
How can I do it using XMLTextReader....
Thanks, Vinu
[1121 byte] By [
vinuhyd] at [2007-12-24]
First of all, please , notice that the provided text is not a well-formed xml document, as it has many top-level elements.
Suppose the following were the xml document you were talking about:
<World>
<Country>
<CNo>1</CNo>
<Country>Afghanistan</Country>
<Nationality>Afghan</Nationality>
<ISDCode>93</ISDCode>
<Continent>Asia</Continent>
</Country>
<Country>
<CNo>2</CNo>
<Country>Albania</Country>
<Nationality>Albanian</Nationality>
<ISDCode>355</ISDCode>
<Continent>Europe</Continent>
</Country>
<Country>
<CNo>3</CNo>
<Country>Algeria</Country>
<Nationality>Algerian</Nationality>
<ISDCode>213</ISDCode>
<Continent>Africa</Continent>
</Country>
</World>
Then one way to find the continent, in which a country (say, Albania) is situated is:
/*/*[Country='Albania']/Continent
If you just need the text value of this element, then use:
/*/*[Country='Albania']/Continent/text()
If what you have already is the element:
<Country>Albania</Country>
Then to select its corresponding continent use:
following-sibling::Continent
Or a complete absolute XPath expression will be:
/*/*/Country[.='Albania']/following-sibling::Continent
I would shamelessly recommend using the XPath Visualizer tool for learning XPath just by playing with different XPath expressions.
Hope this helped.
Cheers,
Dimitre Novatchev