Linq to XML Document Traversal

Posted by Perpetualcoder on Stack Overflow See other posts from Stack Overflow or by Perpetualcoder
Published on 2010-04-26T00:55:18Z Indexed on 2010/04/26 1:03 UTC
Read the original article Hit count: 400

Filed under:
|

I have an xml document like this:

<?xml version="1.0" encoding="utf-8" ?>
<demographics>
    <country id="1" value="USA">
        <state id ="1" value="California">
            <city>Long Beach</city>
            <city>Los Angeles</city>
            <city>San Diego</city>
        </state>
        <state id ="2" value="Arizona">
            <city>Tucson</city>
            <city>Phoenix</city>
            <city>Tempe</city>
        </state>
    </country>
    <country id="2" value="Mexico">
        <state id ="1" value="Baja California">
            <city>Tijuana</city>
            <city>Rosarito</city>            
        </state>
    </country>
</demographics> 

How do I setup LINQ queries for doing things like: 1. Get All Countries 2. Get All States in a Country 3. Get All Cities inside a state of a paricular country ?

I gave it a try and I am kind of confused when to use Elements["NodeName"] and Descendants etc. I know I am not the brightest XML guy around. Is the format of the XML file even correct for simple traversal?

© Stack Overflow or respective owner

Related posts about linq-to-xml

Related posts about c#3.0