xml changing the value of an attribute

前端 未结 3 544
有刺的猬
有刺的猬 2020-12-12 02:46

I have the following text in xml file:


    
        
    

        
相关标签:
3条回答
  • 2020-12-12 03:03

    You could load the file into an XmlDocument, select the attribute using XPath, and write it back out. This is a lot more complex, but probably the "right" solution for production code.

    If you have multiple files or multiple occurrences to replace, a RegEx might be an easier option - this would likely be faster and shorter code, but it's not as descriptive. If what you're doing is (say) writing a tool for non-production use (say, to transform a bunch of config files for use on different machines) this is probably reasonable.

    0 讨论(0)
  • 2020-12-12 03:11

    You could pass the XML trough this basic XSL stylesheet:

    <xsl:stylesheet 
      version="1.0" 
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    >
      <!-- the identity template copies everything verbatim -->
      <xsl:template match="node() | @*">
        <xsl:copy>
          <xsl:apply-templates select="node() | @*" />
        </xsl:copy>
      </xsl:template>
      <!-- only LibraryDirectory attributes get a new value -->
      <xsl:template match="@LibraryDirectory">
        <xsl:copy>
          <xsl:value-of select="'the text here to be changed'" />
        </xsl:copy>
      </xsl:template>
    </xsl:stylessheet>
    

    To apply a stylesheet to your XML document, you could use the XslCompiledTransform class.

    0 讨论(0)
  • 2020-12-12 03:29
    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.

    0 讨论(0)
提交回复
热议问题