Reputation: 2329
I am trying to get a specific value from an xml. When I iterate over the nodes, the value is never returned. Here is the xml sample
<Fields>
<Field FieldName="NUMBER">
<String>1234</String>
</Field>
<Field FieldName="TYPE">
<String>JAVA</String>
</Field>
<Field FieldName="ATYPE">
<String>BB</String>
</Field>
</Fields>
Here is what I have attempted based on this online resource that looks like my sample xml file
private static void updateElementValue(Document doc) {
NodeList employees = doc.getElementsByTagName("Field");
Element emp = null;
//loop for each
for(int i=0; i<employees.getLength();i++){
emp = (Element) employees.item(i);
System.out.println("here is the emp " + emp);
Node name = emp.getElementsByTagName("NUMBER").item(0).getFirstChild();
name.setNodeValue(name.getNodeValue().toUpperCase());
}
}
This is the online resource guiding my attempts
https://www.journaldev.com/901/modify-xml-file-in-java-dom-parser
Please assist
Upvotes: 0
Views: 476
Reputation: 943
If you want to get a specific value from XML, XPath API may be more convenient in compare to DOM parser API. Here an example for retrieving value of a "String" elements, which are children of "Field" elements, having attribute "FieldName" with value "NUMBER":
// parse XML document from file
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new FileInputStream(fileName));
// prepare an XPath expression
XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("/Fields/Field[@FieldName='NUMBER']/String");
// retrieve from XML nodes using XPath
NodeList list = (NodeList)xpath.evaluate(doc, XPathConstants.NODESET);
// iterate over resulting nodes and retrieve their values
for(int i = 0; i < list.getLength(); i ++) {
Node node = list.item(i);
// udate node content
node.setTextContent("New text");
}
// output edited XML document
StringWriter writer = new StringWriter(); // Use FileWriter to output to the file
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
System.out.println(writer.toString());
Upvotes: 1