xml更改属性的值

Nig*_*ker 2 .net c# xml

我在xml文件中有以下文本:

<Config Builder="LP Wizard">
    <Libraries>
        <Library Name="XCAMSource"/>
    </Libraries>
    <InputFormats>
        <XCAM Format="XCAM" LibraryDirectory="C:\XCAM"/>
    </InputFormats>
    <OutputFormats>
        <Pads Version="PADS 5.0" ExportAscii="false" LibraryGenerate="true" ExtendedLayers="false" AlphaLoc="PART TYPE" Format="PADS" LibraryDirectory="c:\XCAM\OUTPUT" DirectoryStructure="false" Units="Millimeters" NewCodeVersion="false" usrLayerNameElecT="1" usrLayerNameElecB="2" usrLayerNameSilk="26" usrLayerNameSilkb="29" usrLayerNameCY="20" usrLayerName3D="25" usrLayerNameAssy="27" usrLayerNameAssyb="30" usrLayerNamePmask="23" usrLayerNameSmask="21" usrLayerNameSmaskb="28" DirectImport="false"/>
    </OutputFormats>
</Config>
Run Code Online (Sandbox Code Playgroud)

我需要更改位于其下的文本"C:\ XCAM" LibraryDirectory=.

这样做的聪明方法是什么,我只是不想进行字符串搜索LibraryDirectory= ,然后搜索第一个和最后一个"然后更改文本."

Dar*_*rov 7

var doc = XDocument.Load("test.xml");
doc.Root.Element("XCAM").Attribute("LibraryDirectory").Value = "new value";
doc.Save("test.xml");
Run Code Online (Sandbox Code Playgroud)

更新:

doc.Root
   .Element("InputFormats")
   .Element("XCAM")
   .Attribute("LibraryDirectory").Value = "new value";
Run Code Online (Sandbox Code Playgroud)

或使用XPATH:

doc.XPathSelectElement("//InputFormats/XCAM")
   .Attribute("LibraryDirectory").Value = "new value";
Run Code Online (Sandbox Code Playgroud)

不要忘记添加使用,System.Xml.XPath因为XPathSelectElement是一个扩展方法.