简体   繁体   中英

Replace data in XML File in Java

I'm trying to replace

<photo>dummy.jpg</photo>

with this

<photo>NewImage_2012-03-22:15.00.00.jpg</photo>

the code looks like this

Element nameElement = (Element) fstNode;
NodeList nameElemList = nameElement.getElementsByTagName("photo");
Element firstElement = (Element) nameElemList.item(0);
NodeList fstNm = firstElement.getChildNodes();
Text newData = doc.createTextNode("NewImage_2012-03-22:15.00.00.jpg");
firstElement.replaceChild(newData, fstNm.item(0));
System.out.println("Data : " + 
  firstElement.getChildNodes().item(0).getNodeValue());

in the output it prints the new photo name, but it doesn't replace the data in the xml file. What am i missing?

Thanks.

use DocumentTraversal,NodeIterator to replace string.

 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                Document doc = docBuilder.parse("/home/riddhish/developerworkspace/SplitString/src/com/updatexmlwithjava/file.xml");           
                DocumentTraversal traversal = (DocumentTraversal) doc;
                Node a = doc.getDocumentElement();
                System.out.println("Chield node length ="+a.getChildNodes().getLength());
                NodeIterator iterator = traversal.createNodeIterator(a, NodeFilter.SHOW_ELEMENT, null, true);
                Element b = null;
                for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
                    Element e = (Element) n;                
                    if ("parent tag".equals(e.getTagName())) {
                        System.out.println(""+e.getTagName() +" "+ e.getTextContent());
                        b = e;
                    } else if ("photo".equals(e.getTagName()) && "dummy.jpg".equals(e.getTextContent()) && b != null) {
                        e.setTextContent("NewImage_2012-03-22:15.00.00.jpg");
                        //a.removeChild(b);
                    }
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM