1

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
  • Added regular c# tag to get better visibility and more responses. Commented Mar 29, 2010 at 15:49

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.