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.
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));
}
}