开发者

parse Linq To Xml with attribute nodes

开发者 https://www.devze.com 2022-12-24 19:53 出处:网络
I am having xml with following structure <ruleDefinition appId=\"3\" customerId = \"acf\"> <node alias=\"element1\" id=\"1\" name=\"department\">

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="mik开发者_StackOverflow社区e" />
        <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?


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);
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消