开发者

LINQ to XML get value from anywhere using hierarchy patterns

I'm trying to parse a poorly formatted xml document. There are some patterns in the xml such as for eg. I want to get the value of a node Name that has parent MyParentNode. Then later down, there is another node Name that I'd like to get under Farm. For eg.

<Node>
    <MyParentNode>
         <Name>LOL</Name>
         <RandomNode>
              <Farms>
                   <Farm>
                       <Name>MyFarmName</Name>
                   </Farm>
                   <Farm>
                       <Name>MyFarmName2</Name>
                   </Farm>
              </Farms>
         </RandomNode>
    </MyParentNode>
</Node>

So from this, I'd like to extract an array that looks like this:

public class SomeClass{
     public string ParentName {get; set;} // MyParentNode->Name
     public string Name {get; set;} //RandomNode->Farms->Farm->Name
}
开发者_运维百科

I basically want to flatten this xml into an array of:

List<SomeClass> list = FlattenXml();
list[0]; //ParentName = LOL, Name = MyFarmName
list[1]; //ParentName = LOL, Name = MyFarmName2

The problem is that some of these data are deep down in the hierarchy and sometimes they are random. But they can be found from the pattern of the Parent node and child node. Could someone show me the code to solve the above problem please?


This works on the XML snippet you have posted.

var result = from node in doc.Descendants("MyParentNode")
             select new
             {
                 ParentName = node.Descendants("Name").First().Value,
                 FarmList = from farm in node.Descendants("Farm")
                            select farm.Element("Name").Value
             };

var flattened = result.SelectMany(a => a.FarmList,
    (a, b) => new SomeClass { ParentName = a.ParentName, Name = b });

Result:

ParentName  Name
LOL         MyFarmName
LOL         MyFarmName2


try this

public class SomeClass
        {
            public string ParentName { get; set; } // MyParentNode->Name
            public List<string> Name { get; set; } //RandomNode->Farms->Farm->Name
        }
        static List<SomeClass> FlattenXml(XElement source)
        {
            List<SomeClass> result;

            result = (from item in source.Elements()
                      select new SomeClass()
                      {
                          ParentName = item.Element("Name").ToString(),
                          Name = (from i in item.Descendants("Farm")
                                      select i.Element("Name").Value).ToList()


                      }).ToList();

            return result;
        }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜