LINQ to XML 使用层次结构模式从任何地方获取价值
我正在尝试解析格式错误的 xml 文档。 xml 中有一些模式,例如:我想获取具有父 MyParentNode
的节点 Name
的值。然后,我想在 Farm
下找到另一个节点 Name
。例如。
<Node>
<MyParentNode>
<Name>LOL</Name>
<RandomNode>
<Farms>
<Farm>
<Name>MyFarmName</Name>
</Farm>
<Farm>
<Name>MyFarmName2</Name>
</Farm>
</Farms>
</RandomNode>
</MyParentNode>
</Node>
因此,从中,我想提取一个如下所示的数组:
public class SomeClass{
public string ParentName {get; set;} // MyParentNode->Name
public string Name {get; set;} //RandomNode->Farms->Farm->Name
}
我基本上想将这个 xml 展平为一个数组:
List<SomeClass> list = FlattenXml();
list[0]; //ParentName = LOL, Name = MyFarmName
list[1]; //ParentName = LOL, Name = MyFarmName2
问题是其中一些数据位于层次结构的深处,有时它们是随机的。但可以从父节点和子节点的模式中找到它们。有人可以告诉我解决上述问题的代码吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这适用于您发布的 XML 片段。
结果:
This works on the XML snippet you have posted.
Result:
试试这个
try this