1

I have been trying to modify values of more than one XML tag in java. So far I am able to get the values of the two nodes that I want to modify but while setting up values it always overrides the first one with the second one.

XML

 <driver>
    <BirthDate>1977-07-18</BirthDate>
    <Age>40</Age>                    
    <Gender>M</Gender>
    <PrimaryResidence>OwnCondo</PrimaryResidence>
 </driver> 

I am trying to change Gender and PrimaryResidence tags.

Code

// Modifies multiple XML nodes
 public static String changeCoreDiscountType(String reqXML) {
        Document document = null;
        String updatedXML = null;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(reqXML));
            document = builder.parse(is);

            XPath xPath = XPathFactory.newInstance().newXPath();
            XPathExpression expression = xPath.compile("/driver/Gender | /driver/PrimaryResidence");
            NodeList nodeList = (NodeList) expression.evaluate(document,XPathConstants.NODESET);

            for(int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                node.setTextContent("F");
                node.setTextContent("OwnCondo");
                String value = node.getTextContent();
            }

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(new StringWriter());
            transformer.transform(source, result);

            updatedXML = result.getWriter().toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return updatedXML;
    }

Any help is appreciated.

1 Answer 1

1

You need to check you are updating the correct node first, e.g.

for(int i = 0; i < nodeList.getLength(); i++) {
    Node node = nodeList.item(i);

    if(node.getNodeName() == "Gender")
        node.setTextContent("F");
    if(node.getNodeName() == "PrimaryResidence")
        node.setTextContent("OwnCondo");
}

Full Demo

Sign up to request clarification or add additional context in comments.

1 Comment

This is what I was looking for. Cool. Thanks for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.