简体   繁体   English

如何使用Linq to XML获取XML的多个相同节点的子节点的值

[英]How to get the values of child nodes of multiple identical nodes of XML with Linq to XML

I have an XML file that looks like this: 我有一个看起来像这样的XML文件:

<injuryRespData>
  <lc01s>
    <lc01>
      <aac001>1</aac001>
      <alca02>2</alca02>
      <aab001>3</aab001>
    </lc01>
    <lc01>
      <aac001>4</aac001>
      <alca02>5</alca02>
      <aab001>6</aab001>
    </lc01>
    <lc01>
      <aac001>7</aac001>
      <alca02>8</alca02>
      <aab001>9</aab001>
    </lc01>
  </lc01s>
</injuryRespData>

I have a Class and List entity: 我有一个Class and List实体:

public class lc01
{
   public string aac001{set;get;}
   public string alca02{set;get;}
   public string aab001{set;get;}
}
List<lc01> list = new List<lc01>();  

How could I get the values of child nodes under multiple lc01 nodes respectively and add to the List collection using Linq to XML? 如何才能分别获取多个lc01节点下的子节点的值,并使用Linq to XML将其添加到List集合中?

You could do this using Descendants and Select methods: 您可以使用DescendantsSelect方法来执行此操作:

List<lc01> list=doc.Root.Descendants("lc01")
                   .Select(e=>new lc01{aac001=(string)e.Element("aac001"),
                                       alca02=(string)e.Element("alca02"),
                                       aab001=(string)e.Element("aab001")
                                      })
                   .ToList();
var xml = @"<injuryRespData>
    <lc01s>
    <lc01>
        <aac001>1</aac001>
        <alca02>2</alca02>
        <aab001>3</aab001>
    </lc01>
    <lc01>
        <aac001>4</aac001>
        <alca02>5</alca02>
        <aab001>6</aab001>
    </lc01>
    <lc01>
        <aac001>7</aac001>
        <alca02>8</alca02>
        <aab001>9</aab001>
    </lc01>
    </lc01s>
</injuryRespData>";

var result = (
    from x in XDocument.Parse(xml).Descendants("lc01").Cast<XElement>()
    select new XmlSerializer(typeof(lc01)).Deserialize(new StringReader(x.ToString()))).ToList();

I solved the problem myself: 我自己解决了这个问题:

var xml = @"<injuryRespData>
    <lc01s>
    <lc01>
        <aac001>1</aac001>
        <alca02>2</alca02>
        <aab001>3</aab001>
    </lc01>
    <lc01>
        <aac001>4</aac001>
        <alca02>5</alca02>
        <aab001>6</aab001>
    </lc01>
    <lc01>
        <aac001>7</aac001>
        <alca02>8</alca02>
        <aab001>9</aab001>
    </lc01>
    </lc01s>
</injuryRespData>";

XElement xmlDoc = XElement.Parse(xml);
List<lc01> lc01List =  new List<lc01>();
lc01List.clear();
foreach (XElement item in RespDoc.Descendants("lc01"))
{
   lc01 temp = lc01()
   {
      aac001 = item.Element("aac001").Value,
      alca02 = item.Element("alca02").Value,
      aab001 = item.Element("aab001").Value
   }
   lc01List.Add(lc01);
}

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

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