我将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)`
我有很多这样的节点,所以我想知道是否有通过'[]'或某种方式访问这些属性的简单方法。
答案 0 :(得分:4)
代码:
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
答案 1 :(得分:1)
这将打印出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")