How to change xml tag value in java?
I am new to working with xml.i used the xml file as follows:
<?xml version="1.0" encoding="UTF-8" ?> - <root> - <key> <Question>Is the color of the car</Question> <Ans>black?</Ans> </key> - <key> <Question>Is the color of the car</Question> <Ans>black?</Ans> </key> - <key> <Question>Is the news paper</Question> <Ans>wallstreet?</Ans> </key> - <key> <Question>fragrance odor</Question> <Ans>Lavendor?</Ans> </key> - <key> <Question>Is the baggage collector available</Question> <Ans /> </key> </root>
from the above xml I would like to change only
<Ans>wallstreet?</Ans> as <Ans>WonderWorld</Ans>.
How can I change the wallstreet? How is WonderWorld? through my java application.
I wrote a java method as shown below:
public void modifyNodeval(){ try{ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File(path)); Node nodes1 = doc.getElementsByTagName("*"); for(int j=0;j<nodes1.getLength();j++) { //Get the staff element by tag name directly Node nodes = doc.getElementsByTagName("key").item(j); //loop the staff child node NodeList list = nodes.getChildNodes(); for (int i = 0; i != list.getLength(); ++i) { Node child = list.item(i); if (child.getNodeName().equals("Ans")) { child.getFirstChild().setNodeValue("WonderWorld") ; System.out.println("tag val modified success fuly"); } } } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(path); transformer.transform(source, result); } catch (Exception e) { e.printStackTrace(); } }
using the code above, I can change the entire text of the tag as a wonderful world, but I want me to change only the wallstreet? like WonderWorld.
any body please help me .....
You are not checking if the value of the node is "wallstreet?" - so it just changes every first child node.
String str = child.getFirstChild( ).getNodeValue( ); if ( "wallstreet?".compareTo( str ) == 0 ) { child.getFirstChild( ).setNodeValue( "WonderWorld" ); System.out.println( "tag val modified success fuly" ); }