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

nkuebelbeck
  • 273
  • 2
  • 5
  • 15
  • 1
    I suggest using an XPath query on it. Syntax would be something like `/root/program/params/param[@name='name2']`. See [this question](http://stackoverflow.com/questions/6538883/java-how-to-locate-an-element-via-xpath-string-on-org-w3c-dom-document) for the xpath setup – Gus Jul 19 '13 at 19:24

2 Answers2

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());
    }

}
bdoughan
  • 147,609
  • 23
  • 300
  • 400
sevensevens
  • 1,703
  • 16
  • 27
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
     }
  }
Ilya
  • 29,135
  • 19
  • 110
  • 158