给定一个XElement,如何在给定XPath的情况下检索对另一个相对XElement/Xattribute的引用?

Ror*_*ker 4 .net xml xelement xpath

给出以下XML:

<SomeXML>
    <Element1>
        <Element2 Attribute3="Value4" />
    </Element1
</SomeXML>
Run Code Online (Sandbox Code Playgroud)

...以及对"SomeElement"和XPath"Element1/Element2/@ Attribute3"的XElement引用

如何检索对Attribute3的引用,以便我可以改变它的值(使用Xpath)?

XPath是一个检索的设置,因此是我找到相关节点的唯一方法.

Ant*_*nes 6

添加using System.Xml.XPath到您需要执行此操作的代码文件中.

然后你可以使用这样的代码: -

 var attrib3 = someElement.XPathEvaluate("Element1/Element2/@Attribute3") as XAttribute;
 if (attrib3 != null)
     attrib3.Value = "new value";
Run Code Online (Sandbox Code Playgroud)