1

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.

3
  • 4
    You have to store the data back to the file, similar to the way you loaded it... Find some info here: stackoverflow.com/questions/3498190/how-to-create-xml-file Commented Mar 22, 2012 at 12:10
  • If it's an option I would suggest using JAXB. Using JAXB just seems to make creating,manipulating,saving XML a lot easier, to me anyway. Commented Mar 22, 2012 at 13:55
  • can you please load your xml file.. Commented Mar 26, 2012 at 11:26

1 Answer 1

0

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);
                    }
                }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.