I have to parse a xml file in which I have many name value pairs. I have to update the value in case it matches a given name.
I opted for DOM parsing as it can easily traverse any part and can quickly update the value. It is however giving me some wired results when I am running it on my sample file.
I am new to DOM so if someone can help it can solve my problem. I tried various but all resulting in either null values for content or #text node name.
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(xmlFilePath);
Node NVPairs = document.getElementsByTagName("NVPairs").item(0);
NodeList nodes = NVPairs.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if(node.hasChildNodes())
{
if ("Tom".equals(node.getFirstChild().getTextContent())) {
node.getLastChild().setTextContent("2000000");
}
}
}
Sample xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><application>
<NVPairs>
<nameValuePair>
<name>Tom</name>
<value>12</value>
</nameValuePair>
<nameValuePair>
<name>Sam</name>
<value>121</value>
</nameValuePair>
</NVPairs>
No comments:
Post a Comment