Search code examples
c#xmlxmldocument

XMLDocument going deep


Right now I have my code similar to this (actually one level deeper). If the company name is equal to the node of company then create a node list from it (as I need to populate a drop down box with all of the details) ---Not using 3.5 for this project :(

XmlNodeList elemList = xmlDoc.GetElementsByTagName("company");
foreach (XmlNode node in elemList)
{
    if (node.Attributes[0].Value == company)
    {   
        foreach (XmlNode child in node.ChildNodes)
        {
            foreach (XmlNode detail in child.ChildNodes)
            {
                ddlCodes.Items.Add(detail.Value.ToString());
            }
        }
    }
}

Not really liking all those foreach statements, just wondering if there is a cleaner way. Here is how my xml looks like

<companies>
    <company id="company1">
       <code>12</code>
       <detail>detail of 12 code</detail>
    </company>
    <company id="company2">
       <code>15</code>
       <detail>detail of 15 code</detail>
    </company>
</companies>

Solution

  • Have a look at XPath and the XPathNavigator class, it provides you with a query language for XML

    Or you could use Linq to XML if you want but that depends on the .net framework you're using.