繁体   English   中英

如何从嵌套的xml节点获取属性值?

[英]How to get attributes values from nested xml node?

我有这样格式化的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)`

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

码:

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

这将打印出所有在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")

暂无
暂无

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

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