C# 在XmlNode数组中按名称查找值
我有以下XML:C# 在XmlNode数组中按名称查找值,c#,asp.net,arrays,xml,xmlnode,C#,Asp.net,Arrays,Xml,Xmlnode,我有以下XML: <UserArea> <Property> <NameValue name="amperage" type="StringType">1</NameValue> </Property> <Property> <NameValue name="attachments" type="StringType">2</NameValue>
<UserArea>
<Property>
<NameValue name="amperage" type="StringType">1</NameValue>
</Property>
<Property>
<NameValue name="attachments" type="StringType">2</NameValue>
</Property>
<Property>
<NameValue name="noOfBolts" type="StringType">3</NameValue>
</Property>
<Property>
<NameValue name="boreSize" type="StringType">4</NameValue>
</Property>
</UserArea>
我有大约250个属性元素,所以我不想在这里使用
foreach
。您可以始终使用XPath选择节点
XmlNodeList nodes = userAreaNode.SelectNodes("//Property/NameValue[@name='attachments']");
你可以很容易地使用它。将xml解析为,然后遍历
根
子体,获得第一个元素的值,其名称
属性等于附件值
var document=XDocument.Parse(xml);
var结果=
document.Root?.subjections()
.FirstOrDefault(e=>e.HasAttributes&&e.Attribute(“名称”)?.Value==“附件”)?.Value??
字符串。空;
它应该是//Property/NameValue[@name='attachments'],因为name属性在NameValue元素上。另外,如果您能保证每个NameValue只有一个实例,您可以使用SelectSingleNode返回单个XmlNode。
XmlNodeList nodes = userAreaNode.SelectNodes("//Property/NameValue[@name='attachments']");