繁体   English   中英

使用linq c#在单个节点上返回多个具有相同名称的xml子元素#

[英]Returning multiple xml Children with same name on single node using linq c#

我有以下XML,并希望返回所有“学校”的孩子,但我只有第一个。 (jeffersion / 08.36)我高高低低地抬起头来。 我错过了什么?

<users>
  <user>
    <role>janitor</role>
    <schools>
      <school_name>jefferson</school_name>
      <keycode>80.36</keycode>
      <school_name>mainline</school_name>
      <keycode>64.36</keycode>
      <school_name>south side</school_name>
      <keycode>31</keycode>
    </schools>
  </user>
</users>

这只返回第一条记录。

var results= from schools in myXmlDoc.Descendants("schools")
                   select new 
                   {
                       SchoolName = schools.Element("school_name").Value,
                       KeyCode = schools.Element("keycode").Value
                   };

我也尝试过:

var results= (from schools in myXmlDoc.Descendants("schools")
                   select new 
                   {
                       SchoolName = schools.Element("school_name").Value,
                       KeyCode = schools.Element("keycode").Value
                   }.ToList();

这只获得了第一所学校的价值观:

var schools = (from c in xml.Descendants("user")
                      select new
                      {
                          Name = c.Element("role").Value,
                          Fields = c.Elements("schools")
                              .Select(f => new
                              {
                                  SchoolName = f.Element("school_name").Value,
                                  Keycode = f.Element("keycode").Value
                              }).ToArray()
                      }).ToList();

这可能会有所帮助:

var result =来自XElement.Load中的c(“Student.xml”)。元素(“学校”)选择c;

//对foreach执行查询(结果是var个学生){//做某事}

源中只有一个<schools>元素,这就是为什么仅返回一个条目的原因。 XML的结构不是特别好 - 最好有一个包含每个school_name / keycode对的<school>元素。 但是,假设您必须忍受它,那么以下方法应该起作用:

var results= from school in myXmlDoc.Descendants("school_name")
               select new 
               {
                   SchoolName = school.Value,
                   KeyCode = school.ElementsAfterSelf("keycode").First().Value
               };

暂无
暂无

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

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