1
<root>
<program name="SomeProgramName">
    <params>
        <param name='name'>test</param>
        <param name='name2'>test2</param>
    </params>
</program>
</root>

I have the above xml doc. I need to change the value of test to a new value

I read in the xml doc as

String xmlfile = "path\\to\\file.xml"
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlfile);

//get the params element
Node params = doc.getElementsByTagName("params").item(0);

//get a list of nodes in the params element
NodeList param = params.getChildNodes();

This is where I am stuck. I can't find a method to set the value of one of the param elements by the "name"

I'm using java 1.7

1
  • 1
    I suggest using an XPath query on it. Syntax would be something like /root/program/params/param[@name='name2']. See this question for the xpath setup Commented Jul 19, 2013 at 19:24

2 Answers 2

3

You'll need to type each Node to type Element to be able to set the text and attributes. You might want to look at XPath, which simplifies things like this.

import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        String xmlfile = "src/forum17753835/file.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(xmlfile);

        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        Element element = (Element) xpath.evaluate("/root/program/params/param[@name='name2']", doc, XPathConstants.NODE);
        System.out.println(element.getTextContent());
    }

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

1 Comment

xpath looks interesting. I will look into this solution
0
  NodeList params = doc.getElementsByTagName("param");
  for (int i = 0; i < params.getLength(); i++)
  {
     if (params.item(i).getAttributes().getNamedItem("name").getNodeValue().equals("name2"))
     {
        // do smth with element <param name='name2'>test2</param>
        // that is params.item(i) in current context
     }
  }

Comments

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.