簡體   English   中英

為具有子項屬性的子項查詢XElements

[英]Quering XElements for children with children attributes

這是XML大綱:

<Root> 
  <Thing att="11">    
    <Child lang="e">  
       <record></record>
       <record></record>
       <record></record>  
   </Child >
   <Child lang="f">  
       <record></record>  
       <record></record>                
       <record></record>
   </Child > 
 </Thing> 
</Root>

我有以下內容:

TextReader reader = new StreamReader(Assembly.GetExecutingAssembly()
                 .GetManifestResourceStream(FileName));

   var data = XElement.Load(reader);
foreach (XElement single in Data.Elements())
 {
      // english records
      var EnglishSet = (from e in single.Elements("Child")
         where e.Attribute("lang").Equals("e")
        select e.Value).FirstOrDefault();
}

但我什么都沒回來。 我希望能夠為每個“Thing”選擇“Child”,其中屬性“lang”等於一個值。

我也嘗試了這個,但沒有奏效。

var FrenchSet = single.Elements("Child")
.Where(y => y.Attribute("lang").Equals("f"))
.Select(x => x.Value).FirstOrDefault();

您正在檢查XAttribute對象是否等於字符串"e"
由於XAttribute對象永遠不等於字符串,因此它不起作用。

您需要檢查XAttribute對象的Value ,如下所示:

where y => y.Attribute("lang").Value == "e"

您正在將屬性對象與字符串“e”進行比較,而不是attrbute對象的值。 您還返回節點的值而不是節點的值。 由於該值為空,因此您只需獲取空字符串。

試試這個:

var EnglishSet = (from e in single.Elements("Child")
                  where e.Attribute("lang").Value == "e"
                  select e).FirstOrDefault();
var EnglishSet = (from e in single.Elements("Child")
         where e.Attribute("lang").Value.Equals("e")
        select e).FirstOrDefault();

正如Slaks所說,你正在檢查屬性不是它的值是“e”。 您也不需要select e.Value因為“Child”節點沒有具有“記錄”子節點的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM