Java: modify XML file (extended)

I needed a method to modify xml file, preserving the structure and replacing only certain attributes and nodes content.
Also, I needed a possibility to add dynamically inner xml content.
Here is a pretty wonderful solution for simple xml data updating How To Modify XML File In Java – (DOM Parser).
I added a mechanism to determine dynamically added xml data.

<config>
<server url="server.com" port="443" />
<users number="4" name_pattern="test" />
<log dir="c:\testfile\" file=""/>
<scenarios>
<scenario name="Test #1" class="testOne" active="true">
<limits>
<limit test="5" number="9" />
<limit test="3" number="6" />
<limit test="2" number="11" />
</limits>

</scenario>
<scenario name="Test #2" class="testTwo" active="false">
</scenario>

</scenarios>
</config>

And here is the modified class for modification of this xml file:

 
private void UpdateConfigFile()
{
try {
String filepath = configFileName;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);

Node serverNode = doc.getElementsByTagName("server").item(0);
NamedNodeMap serverNodeAttrMap = serverNode.getAttributes();
Node serverNodeUrl = serverNodeAttrMap.getNamedItem("url");
Node serverNodePort = serverNodeAttrMap.getNamedItem("port");
String[] serverAtrs = serverUrl.getText().split(":");
serverNodeUrl.setTextContent(serverAtrs[0]);
serverNodePort.setTextContent(serverAtrs[1]);

Node usersNode = doc.getElementsByTagName("users").item(0);
NamedNodeMap usersNodeAttrMap = usersNode.getAttributes();
Node usersNodeNumber = usersNodeAttrMap.getNamedItem("number");
Node usersNodeNamePattern = usersNodeAttrMap.getNamedItem("name_pattern");
usersNodeNumber.setTextContent(usersNumber.getText());
usersNodeNamePattern.setTextContent(usersNamePattern.getText());

// loop the staff child node
NodeList list = doc.getElementsByTagName("scenario");
Enumeration<AbstractButton> buttons = bg.getElements();

for (int i = 0; i < list.getLength(); i++) {
Scenario scenario =classes.get(i);
AbstractButton abstractButton = buttons.nextElement();
Node node = list.item(i);
NamedNodeMap attr = node.getAttributes();
Node nodeAttr = attr.getNamedItem("active");
String active = "false";
if (abstractButton.isSelected())
active = "true";
nodeAttr.setTextContent(active);

JTextArea jTextArea = dataSourceList.get(i);
String dataSource = jTextArea.getText().replaceAll(">[\\n\\t\\s]*<","><");
if (!dataSource.equals(""))
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document docdataSource = db.parse(new ByteArrayInputStream(dataSource.getBytes("UTF-8")));
Node e = docdataSource.getDocumentElement();

Element elementDataSource = doc.createElement(e.getNodeName());

//Here we detect if element has child nodes.
if (e.hasChildNodes())
{
NodeList childNodeList = e.getChildNodes();
for(int childInt = 0; childInt< childNodeList.getLength(); childInt++)
{
Node childNode = childNodeList.item(childInt);
if (!childNode.equals(""))
{
NamedNodeMap childNodeAttrMap = childNode.getAttributes();
Element childElement = doc.createElement(childNode.getNodeName());
for (int childNodeInt = 0; childNodeInt < childNodeAttrMap.getLength(); childNodeInt++)
{
Node childNodeAttribute = childNodeAttrMap.item(childNodeInt);
Attr id=doc.createAttribute(childNodeAttribute.getNodeName());
id.setValue(childNodeAttribute.getNodeValue());
childElement.setAttributeNode(id);

}
elementDataSource.appendChild(childElement);
}
}
}

node.setTextContent("");
node.appendChild(elementDataSource);
}
}

// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);

System.out.println("Done");

} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}

Leave a Reply

%d bloggers like this: