我想使用C#和LINQ XML读取XML文件中的属性,但无法检索深度嵌套在树中的值。我试图得到的价值是<Value>
的内容<DisplayName>Add Your Comments</DisplayName>
附近。每个<OrderProduct id=???>
可能有自己的意见。在XML文件中检索深嵌套值
我可以阅读使用LINQ的XML文件中的其他属性,但我很困惑如何去读这么深的嵌套。
谢谢。
<?xml version="1.0" encoding="utf-16"?>
<OrderXml>
<Order>
<OrderProducts>
<OrderProduct id="1">
.
.
.
</OrderProduct>
<OrderProduct id="2">
<PropertyValues>
<PropertyValue>
<Property id="10786">
<DisplayName>Base</DisplayName>
</Property>
<Value />
</PropertyValue>
<PropertyValue>
<Property id="10846">
<DisplayName>Add Your Comments</DisplayName>
</Property>
<Value>this is a comment</Value>
</PropertyValue>
</PropertyValues>
</OrderProduct>
</OrderProducts>
</Order>
</OrderXml>
这是我到目前为止的代码。我可以检索“添加你的评论”部分,但我被困在如何获得跟随它的部分。
string productOrderID = "";
string productName = "";
XElement xelement;
xelement = XElement.Load (@"D:\Order.xml");
IEnumerable<XElement> Products = xelement.Descendants ("OrderProduct");
foreach (var order in Products)
{
productOrderID = order.Attribute ("id").Value;
productName = order.Element ("Product").Element ("Name").Value;
Console.WriteLine ("productOrderID: {0}", productOrderID);
Console.WriteLine ("productName: {0}", productName);
Console.WriteLine ("");
IEnumerable<XElement> PropertyValues = xelement.Descendants ("PropertyValues").Elements ("PropertyValue");
foreach (var propValue in PropertyValues.Elements ("Property").Elements ("DisplayName"))
{
Console.WriteLine ("Property ID: {0}", propValue.Value);
if (propValue.Value == "Add Your Comments")
{
Console.WriteLine ("---");
}
}
}
你说的 “如此之深” 呢?你可以通过调用Decendants()方法来获取任何XContainer的所有嵌套XElement,并执行以下过滤: – Alireza