XML get/set node by attribute value
I've seen several posts regarding XML processing with Java, however none that I've found address my current problem.
I've developed an XMLFileHandler class that loads a given xml file into a Document object, and supports some basic methods such as getRootElement(), getChildNode(), getChildNodes(), getNodeAttributeValue(), etc., etc., etc....
This behaviour has been sufficient enough for accessing nodes/values/attributes in the XML document, but my client has now added a requirement to enable editing of some of these values within the XML document.
I've tried (and failed) at developing a method to do this. The XML file is in the following format:
<?xml version="1.0" encoding="UTF-8" ?>
<location id="1" name="location_name">
<b>some other text</b>
Where the attributes 'id' AND 'name' can (each) uniquely identify EVERY 'location' node.
So, the required functionality would be to design a method that can get a 'location' node by a given 'location_name' attribute value, and then set both the 'a' and 'b' sub-node values, and save the changes to the XML file.
Any suggestions or pointers would be great!
Thanks for your help in advance.
Re: XML get/set node by attribute value
I was able to solve this using XPath:
1) evaluate an XPath statement that returns the node in question ("//location[@name='value']")
2) iterate the returned NodeList object to access the nodes 'ID' attribute (must be defined as ID in referenced .dtd)
3) Element location = document.getElementById( id_from_above_step );
4) iterate the 'location' element's child nodes
5) if the node name is equal to that I'm searching for, .setTextContent( "some_new_value" );
6) save changes to file via Transformer object
Hoping this may help others in the future.