用Java替换XML文件中的数据

时间:2012-03-22 12:07:03

标签: java xml dom

我正在尝试替换

<photo>dummy.jpg</photo>

用这个

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

代码看起来像这样

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());

在输出中打印新的照片名称,但它不会替换xml文件中的数据。我错过了什么?

感谢。

1 个答案:

答案 0 :(得分:0)

使用DocumentTraversal,NodeIterator替换字符串。

 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);
                    }
                }