2013-09-24 28 views
1

我想使用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 ("---"); 
    } 
    } 
} 
+0

你说的 “如此之深” 呢?你可以通过调用Decendants()方法来获取任何XContainer的所有嵌套XElement,并执行以下过滤: – Alireza

回答

3

您可以使用Descendants来搜索文档节点,无论他们在哪里:

string name = "Add Your Comments"; 
var value = xdoc 
    .Descendants("PropertyValue") 
    .Where(pv => (string)pv.Element("Property").Element("DisplayName") == name) 
    .Select(pv => (string)pv.Element("Value")) 
    .FirstOrDefault(); 

输出:

this is a comment 
+0

xdoc.Descendants(“// PropertyValue”)“//”在这里做什么? – Alireza

+0

@Alireza已经修复了 - 我之前试过xpath,忘了修改 –

+0

好的,这种情况下的Stackoverflow约定是什么?我应该删除我的评论吗? – Alireza