Reputation: 283
<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
Upvotes: 1
Views: 1015
Reputation: 1750
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());
}
}
Upvotes: 3
Reputation: 29693
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
}
}
Upvotes: 0