【问题标题】:How to get attributes values from nested xml node?如何从嵌套的 xml 节点获取属性值?
【发布时间】:2010-12-27 10:59:54
【问题描述】:

我的 XElement 对象格式如下:

<Setting guid="3bcedf55-b75f-456b-b90a-a92cbbb022ga">
    <PatientFieldList>
        <PatientFieldSetting PatientName="UserDecision" PatentFieldLength="64" />
        <PatientFieldSetting PatientName="prohibited" PatentFieldLength="128" />
    </PatientFieldList>
</Setting>

我必须获取所有节点中所有属性的值,但我不知道如何:/ 我试过了

xml.Elements("PatientFieldList")

xml.Descendants("PatientsSettingsFieldsList").Where(x => x.Attribute("PatentFieldLength").Value == 64)`

我有很多这样的节点,所以我想知道是否有简单的方法可以通过“[]”或其他方式访问这些属性。

【问题讨论】:

    标签: c# xml linq-to-xml xelement


    【解决方案1】:

    代码:

    using System;
    using System.Linq;
    using System.Xml.Linq
    
    var xml = "<Setting ...";
    var doc = XElement.Parse(xml);
    int i; // for int parse
    var q = from node in doc.Descendants("PatientFieldSetting")
            let name = node.Attribute("PatientName")
            let length = node.Attribute("PatentFieldLength")
            select new { Name = (name != null) ? name.Value : "", Length = (length != null && Int32.TryParse(length.Value, out i)) ? i : 0 };
    
    foreach (var node in q)
    {
        Console.WriteLine("Name={0}, Length={1}", node.Name, node.Length);
    }
    

    输出:

    Name=UserDecision, Length=64
    Name=prohibited, Length=128
    

    【讨论】:

      【解决方案2】:

      这将打印出在您的 xml 中具有属性的所有节点的属性:

      XDocument doc = //your data
      
      var q = from node in doc.Descendants()
              where node.Attributes().Count() > 0
              select new {NodeName = node.Name, Attributes = node.Attributes()};
      
      foreach (var node in q)
      {
          Console.WriteLine( node.NodeName );
          foreach (var attribute in node.Attributes)
          {
              Console.WriteLine(attribute.Name + ":" + attribute.Value);
          }
          Console.WriteLine();
      }
      

      如果您只希望 PatientFieldSetting 节点过滤名称:

      from node in doc.Descendants("PatientFieldSetting")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-14
        相关资源
        最近更新 更多