Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best way to change one value in XML files in Java?

Tags:

java

xml

xslt

jdom

I have an XML file and I know the node name I need to change the value for.

The nodename is ipAddress.

I can use JDOM, get document, get node and change the value and write it or I can write an XSLT file.

The code changing value goes from Java, so my question is which option is better? The size of the XML file can be different.

Another XSLT-related question: Is it possible to write an XSLT file such that I will not be listing all nodes that are in XML but will just specify like if node == ipAddress, then take the new value, and how would I apply the XSLT transformation from Java?

Thank you.

like image 384
yart Avatar asked Jan 12 '11 18:01

yart


People also ask

How do you add an attribute to an existing XML file in Java?

Add a new attribute to the element, using setAttribute(String name, String value) . Call void prettyPrint(Document xml) method of the example. The method gets the xml Document and converts it into a formatted xml String, after transforming it with specific parameters, such as encoding.

How do you write data to XML file in Java?

Write XML to a file Steps to create and write XML to a file. Create a Document doc . Create XML elements, attributes, etc., and append to the Document doc . Create a Transformer to write the Document doc to an OutputStream .

How can I change XML format?

To access XML formatting options, choose Tools > Options > Text Editor > XML, and then choose Formatting.


2 Answers

You could use the standard org.w3c.dom APIs to get a DOM. Then get the node using the standard javax.xml.xpath APIs. And then use the javax.xml.transform APIs to write it back out.

Something like:

import java.io.File;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import org.w3c.dom.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document document = dbf.newDocumentBuilder().parse(new File("input.xml"));

        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        XPathExpression expression = xpath.compile("//A/B[C/E/text()=13]");

        Node b13Node = (Node) expression.evaluate(document, XPathConstants.NODE);
        b13Node.getParentNode().removeChild(b13Node);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new DOMSource(document), new StreamResult(System.out));
    }
}
like image 138
bdoughan Avatar answered Oct 13 '22 20:10

bdoughan


XSLT solution:

<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="pNewIpAddress" select="'192.68.0.1'"/>

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

  <xsl:template match="ipAddress/text()">
  <xsl:value-of select="$pNewIpAddress"/>
  </xsl:template>
</xsl:stylesheet>

When this transformation is applied on any document, all nodes of the document are copied "as-is" except for the text-node child of any ipAddress element (regardless where this element is in the document). The latter is replaced with the value of an externally provided parameter, named $pNewIpAddress.

For example, if the transformation is applied against this XML document:

<t>
    <a>
        <b>
          <ipAddress>127.0.0.1</ipAddress>
        </b>
        <c/>
    </a>
    <d/>
</t>

the wanted, correct result is produced:

<t>
   <a>
      <b>
         <ipAddress>192.68.0.1</ipAddress>
      </b>
      <c/>
   </a>
   <d/>
</t>

There are many Java-based XSLT processors and the proper place to understand how they can be invoked from Java is their documentation. One of the best such XSLT processors is Saxon and its documentation can be found at:

http://www.saxonica.com/documentation/documentation.xml

like image 43
Dimitre Novatchev Avatar answered Oct 13 '22 20:10

Dimitre Novatchev