views:

223

answers:

2

I am having xml with following structure

<ruleDefinition appId="3" customerId = "acf">
    <node alias="element1" id="1" name="department">
        <node alias="element2" id="101" name="mike" />
        <node alias="element2" id="102" name="ricky" />
        <node alias="element2" id="103" name="jim" />
    </node>
</ruleDefinition>

Here nodes are differentiated using alias and not with node tag. As you can see top level node element1 has same node name "node" as element2. I want to parse this XML based on attribute alias.

What should be the Linq-To-Xml code (using C#)to acheive this?

+1  A: 

You could do something like this:

XDocument doc = XDocument.Parse(YourXML);    
var nodes = doc.Descendants("node").Where(x => x.Attribute("alias").Value == "element1");

Which will find all the nodes whose alias attribute is element1.

Matt Dearing
+2  A: 

This is a method of parsing the data structure into items that contain an Element1 string property and an IEnumerable Element2 property, which contains your multiple pieces of element2 data.

string xml = @"<ruleDefinition appId=""3"" customerId = ""acf""> 
    <node alias=""element1"" id=""1"" name=""department"">
        <node alias=""element2"" id=""101"" name=""mike"" /> 
        <node alias=""element2"" id=""102"" name=""ricky"" />
        <node alias=""element2"" id=""103"" name=""jim"" />
    </node>
    </ruleDefinition>";

XDocument document = XDocument.Parse(xml);

var query = from node in document.Descendants("node")
            where node.Attribute("alias").Value == "element1"
            select new
            {
                Element1 = new
                           {
                               Id = node.Attribute("id").Value,
                               Name = node.Attribute("name").Value
                           },

                Element2 = from n in node.Descendants("node")
                           where n.Attribute("alias").Value == "element2"
                           select new
                           {
                               Id = n.Attribute("id").Value,
                               Name = n.Attribute("name").Value
                           }
            };

foreach (var item in query)
{            
    Console.WriteLine("{0}\t{1}", item.Element1.Id, item.Element1.Name);

    foreach (var element2 in item.Element2)
        Console.WriteLine("\t{0}\t{1}", element2.Id, element2.Name);
}
Anthony Pegram
Thanks. It worked perfect...
Manoj