简体   繁体   中英

Replace an attribute in xml with xpath

I want to take an attribute found thru xpath and replace it in the Document.

This is the xml:

<MineX STATE="add">
  <Desc F_CREATOR="admin" F_ENTRYDATE="2010-12-24" F_HEIGHT="0.875" F_ID="1" F_LEFT="1.15625" F_LINE_COLOR="255" F_FORECOLOR="0">
    <F_CUSTOM_BYTES></F_CUSTOM_BYTES>
  </Desc>
</MineX>

With Java, I can retrieve the value like this:

org.w3c.dom.Document xmlDoc = getDoc(path);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();

XPathExpression myExp = xpath.compile("//MineX/Desc/@F_LINE_COLOR");
System.out.println("Line color:" + (String)myExp.evaluate(xmlDoc, XPathConstants.STRING) + "\n");

This prints out: 255

So, what XPath function will allow me to replace the 255, for another string? Or do I need something other than XPath for this?

So, what XPath function will allow me to replace the 255, for another string? Or do I need something other than XPath for this?

XPath is the query language for XML and as such cannot modify an XML document .

In order to modify an XML document one needs to use the programming language (such as XSLT, C#, JS, PHP, ..., etc) that is hosting XPath.

Here is a solution, where the hosting language is XSLT :

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pNewLineColor" select="123"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="@F_LINE_COLOR">
  <xsl:attribute name="{name()}">
    <xsl:value-of select="$pNewLineColor"/>
  </xsl:attribute>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document :

<MineX STATE="add">
    <Desc F_CREATOR="admin"
          F_ENTRYDATE="2010-12-24"
          F_HEIGHT="0.875"
          F_ID="1"
          F_LEFT="1.15625"
          F_LINE_COLOR="255"
          F_FORECOLOR="0">
        <F_CUSTOM_BYTES></F_CUSTOM_BYTES>
    </Desc>
</MineX>

the wanted, correct result is produced :

<MineX STATE="add">
    <Desc F_CREATOR="admin"
          F_ENTRYDATE="2010-12-24"
          F_HEIGHT="0.875"
          F_ID="1"
          F_LEFT="1.15625"
          F_LINE_COLOR="123"
          F_FORECOLOR="0">
        <F_CUSTOM_BYTES></F_CUSTOM_BYTES>
    </Desc>
</MineX>

XPath is a query language for extracting information out of an XML file. As far as I know it is not suited for replacing or editing data in an XML. One way to transform an XML is via XSLT.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM