2017-10-17 128 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)