Faster/shorter 在 C# 中使用指定属性在 XElement 中获取属性值的方法
Faster/shorter way to get an attribute's value in XElement with specified attribute in C#
假设我有这样的东西:
<my-element>
<property name="the property name" value="the value"/>
<property name="some other property name" value="other value"/>
</my-element>
我正在使用以下代码从名称等于的 属性 中获取 "the value" "the property name".
string theValue = (
from p
in myElement.Elements("Property")
where p.Attribute("name").Value == "the property name"
select p.Attribute("value").Value
).FirstOrDefault();
这段代码可以完成工作,但我想知道是否有更好的方法。
我不确定这个主观更好的方法,但你也可以使用Xpath
var xDoc = XDocument.Parse(xmlstring);
var val = (string)xDoc.XPathSelectElement("//property[@name='the property name']")
.Attribute("value");
假设我有这样的东西:
<my-element>
<property name="the property name" value="the value"/>
<property name="some other property name" value="other value"/>
</my-element>
我正在使用以下代码从名称等于的 属性 中获取 "the value" "the property name".
string theValue = (
from p
in myElement.Elements("Property")
where p.Attribute("name").Value == "the property name"
select p.Attribute("value").Value
).FirstOrDefault();
这段代码可以完成工作,但我想知道是否有更好的方法。
我不确定这个主观更好的方法,但你也可以使用Xpath
var xDoc = XDocument.Parse(xmlstring);
var val = (string)xDoc.XPathSelectElement("//property[@name='the property name']")
.Attribute("value");