简体   繁体   English

为具有子项属性的子项查询XElements

[英]Quering XElements for children with children attributes

Here is the XML outline: 这是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>

I have the following: 我有以下内容:

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();
}

But I'm getting back nothing. 但我什么都没回来。 I want to be able to for Each "Thing" select the "Child" where the attribute "lang" equals a value. 我希望能够为每个“Thing”选择“Child”,其中属性“lang”等于一个值。

I have also tried this, which has not worked. 我也尝试了这个,但没有奏效。

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

You're checking whether the XAttribute object is equal to the string "e" . 您正在检查XAttribute对象是否等于字符串"e"
Since an XAttribute object is never equal to a string, it doesn't work. 由于XAttribute对象永远不等于字符串,因此它不起作用。

You need to check the XAttribute object's Value , like this: 您需要检查XAttribute对象的Value ,如下所示:

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

You are comparing the attribute object with the string "e", rather than the value of the attrbute object. 您正在将属性对象与字符串“e”进行比较,而不是attrbute对象的值。 You're also returning the value of the node rather than the node. 您还返回节点的值而不是节点的值。 Since the value is empty, you'll just get the empty string. 由于该值为空,因此您只需获取空字符串。

Try this instead: 试试这个:

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();

As Slaks stated you were checking that the attribute not it's value was "e". 正如Slaks所说,你正在检查属性不是它的值是“e”。 You also don't need select e.Value because the "Child" nodes don't have a value they have "record" children. 您也不需要select e.Value因为“Child”节点没有具有“记录”子节点的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM