XML改变属性的值 [英] xml changing the value of an attribute

查看:242
本文介绍了XML改变属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在XML文件中的以下文字:

 <配置生成器=LP向导>
    <库>
        <图书馆名称=XCAMSource/>
    < /库>
    < InputFormats>
        < XCAM格式=XCAMLibraryDirectory =C:\ XCAM/>
    < / InputFormats>
    < OutputFormats>
        <脚垫版本=PADS 5.0ExportAscii =假LibraryGenerate =真正的ExtendedLayers =假AlphaLoc =部件类型格式=刹车片LibraryDirectory =C:\ XCAM \输出DirectoryStructure =假单位=毫米新的codeVersion =假usrLayerNameElecT =1usrLayerNameElecB =2usrLayerNameSilk =26usrLayerNameSilkb =29usrLayerNameCY =20usrLayerName3D =25usrLayerNameAssy =27usrLayerNameAssyb =30usrLayerNamePmask =23usrLayerNameSmask =21usrLayerNameSmaskb =28DirectImport =FALSE/>
    < / OutputFormats>
< /配置>
 

我需要改变的文字。C:\ XCAM,根据 LibraryDirectory = 坐在

什么是聪明的方式来做到这一点,我只是不希望字符串搜索 LibraryDirectory = 然后搜索第一个和最后,然后更改文本相互之间的关系。

解决方案

  VAR DOC = XDocument.Load(的test.xml);
doc.Root.Element(XCAM)属性(LibraryDirectory)值=新价值。;
doc.Save(的test.xml);
 


更新:

  doc.Root
   .Element(InputFormats)
   .Element(XCAM)
   属性约(LibraryDirectory)值=新价值。
 

或使用XPATH:

  doc.XPathSelectElement(// InputFormats / XCAM)
   属性约(LibraryDirectory)值=新价值。
 

不要忘了用 System.Xml.XPath 作为的 XPathSelectElement 是一个扩展方法。

I have the following text in xml file:

<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>

I need to change the text "C:\XCAM" that sits under LibraryDirectory=.

What is the smart way to do so, I just dont want to string search for LibraryDirectory= and then search for first and last " and then to change the text betweenthem.

解决方案

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


UPDATE:

doc.Root
   .Element("InputFormats")
   .Element("XCAM")
   .Attribute("LibraryDirectory").Value = "new value";

or using XPATH:

doc.XPathSelectElement("//InputFormats/XCAM")
   .Attribute("LibraryDirectory").Value = "new value";

Don't forget to add the using System.Xml.XPath as XPathSelectElement is an extension method.

这篇关于XML改变属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆