Replace attribute in xml with xpath

I want to take the attribute found through xpath and replace it in the document.

This is 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 get a value similar to 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");

It gives out: 255

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

+5
source share
2 answers

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

XPath is a query language for XML and thus cannot modify an XML document .

XML (, XSLT, #, JS, PHP,... ..), XPath.

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

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

, :

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

XPath - XML . , XML. XML - XSLT.

0

All Articles