Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace an attribute in xml with xpath

Tags:

java

xml

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?

like image 405
elcool Avatar asked Dec 24 '10 20:12

elcool


2 Answers

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>
like image 156
Dimitre Novatchev Avatar answered Oct 22 '22 08:10

Dimitre Novatchev


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.

like image 43
Hovercraft Full Of Eels Avatar answered Oct 22 '22 07:10

Hovercraft Full Of Eels