C# 编写XDocument';通过XPath创建属性值
我试图通过给定的XPath将属性值写入现有XDocument。但似乎唯一的方法是获取一个元素,然后调用属性。有没有直接写入属性的方法(在我的例子中,没有将给定的XPath拆分为“/locations/group[@name=“Client:UserData”]”以选择元素,而“/root”以从XElement对象获取属性) 给定XML(作为XDocument):C# 编写XDocument';通过XPath创建属性值,c#,xml,xpath,linq-to-xml,C#,Xml,Xpath,Linq To Xml,我试图通过给定的XPath将属性值写入现有XDocument。但似乎唯一的方法是获取一个元素,然后调用属性。有没有直接写入属性的方法(在我的例子中,没有将给定的XPath拆分为“/locations/group[@name=“Client:UserData”]”以选择元素,而“/root”以从XElement对象获取属性) 给定XML(作为XDocument): 给定XPath: /位置/组[@name=“Client:UserData”]/@root 给定值:“\appserver\ano
给定XPath:
/位置/组[@name=“Client:UserData”]/@root
给定值:“\appserver\anotherDirectory”
预期输出(作为XDocument):
它似乎可以解决您的问题:
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
foreach (XAttribute attr in ((IEnumerable)
yourDocument.XPathEvaluate(yourXPath)).OfType<XAttribute>()) {
attr.Value = yourValue;
}
使用System.Linq;
使用System.Xml.Linq;
使用System.Xml.XPath;
foreach(XAttribute attr in)((IEnumerable)
yourDocument.xpatheevaluate(yourXPath)).OfType()){
属性值=你的值;
}
能否提供XPath查询示例、输入示例和所需输出?你能详细解释一下“分割XPath”是什么意思吗?看。不幸的是,他正在使用XPath编写元素,这不是我想要做的。因为XPathEvaluate返回对象,所以不能对其调用of type()。另一个强制转换为空attr@Tobias,你说得对,我忘了对IEnumerable
进行强制转换。除非XPath查询恰好返回原语类型而不是节点集,否则更新后的代码应该可以工作。
<locations>
<group name="Client:UserData" root="\\appserver\anotherDirectory" required="true">
<path name="some name" path="~\directory\file" required="false" autoCreate="false" />
</group>
</locations>
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
foreach (XAttribute attr in ((IEnumerable)
yourDocument.XPathEvaluate(yourXPath)).OfType<XAttribute>()) {
attr.Value = yourValue;
}