2017-10-17 130 views
0

我有一个XML如下。当路径是d:\ mypath时,我将不得不获取标题。我尝试了低于一个,但它没有按预期给出。我想在LINQ to XML中实现它。提取兄弟节点linq

我的代码:

XDocument xdoc = XDocument.Load(file); 
string mypath = @"D:\\Mypath"; 
var result = xdoc.Descendants("child") 
    .Where(i => (string)i.Element("content").Element("path") == mypath) 
    .Select(i => (string)i.Element("title")).FirstOrDefault(); 

现在我已经完成如下使用XPathSelectElement我的任务,但我有兴趣在LINQ查询:

string a = (string)xdoc.XPathSelectElement(
    "//child/content[path='" + mypath + "']/../doc_attributes/title"); 

示例XML:

<parent> 
    <doc> 
     <order>testorder</order> 
     <preorder>yes</preorder> 
    </doc> 
    <childs> 
     <child> 
      <doc_attributes> 
       <id>090015b3804fb931</id> 
       <title>CTA</title> 
      </doc_attributes> 
      <content> 
       <path>D:\\Mypath</path> 
      </content> 
     </child> 
    </childs> 
</parent> 

回答

1

你很近,你只是忘记检查Value属性

.Where(i => i.Element("content").Element("path").Value == mypath)