I am building a \"XML scanner\" in Java that finds attribute values starting with \"!Here:\". The attribute value contains instructions to replace later. for example I hav
In order to modify some element or attribute values in the XML file, while still being respectful of XML structure, you will need to use a XML parser. It's a bit more involved than just String$replace()...
Given an example XML like:
In order to change the 2 markers !Here, you need
Document,value that contains the string !Here. The xpath expression is //*[contains(@value, '!Here')].do the transformation you want on each selected nodes. Here I just change !Here by What?.
save the modified dom Document into a new file.
static String inputFile = "./beans.xml";
static String outputFile = "./beans_new.xml";
// 1- Build the doc from the XML file
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(new InputSource(inputFile));
// 2- Locate the node(s) with xpath
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xpath.evaluate("//*[contains(@value, '!Here')]",
doc, XPathConstants.NODESET);
// 3- Make the change on the selected nodes
for (int idx = 0; idx < nodes.getLength(); idx++) {
Node value = nodes.item(idx).getAttributes().getNamedItem("value");
String val = value.getNodeValue();
value.setNodeValue(val.replaceAll("!Here", "What?"));
}
// 4- Save the result to a new XML doc
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(new DOMSource(doc), new StreamResult(new File(outputFile)));
The resulting XML file is: