【问题标题】:Issue with upadating xml file using java?使用java更新xml文件的问题?
【发布时间】:2013-04-18 16:31:46
【问题描述】:

//**在 NodeList nList = doc.getElementsByTagName(e); 处得到 null下面是我的xml内容 我试图删除 xml 文件中存在的类似标签。 nList 显示为空。如何解决这个问题?

**

    public class DelElement {
public static String parent;
public static void main(String[] args) {

    try {

        File file = new File("D:/vodafone/parse.xml");

        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder();

        Document doc = dBuilder.parse(file);

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        parent=doc.getDocumentElement().getNodeName();
        if (doc.hasChildNodes()) {

            printNote(doc,doc.getChildNodes());

        }

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

private static void printNote(Document doc, NodeList nodeList) throws TransformerException {



    String file = "D:/vodafone/parse.xml";

    for (int count = 0; count < nodeList.getLength(); count++) {

        Node tempNode = nodeList.item(count);

        // make sure it's element node.
        if (tempNode.getNodeType() == Node.ELEMENT_NODE) {

            // get node name and value
            System.out.println("\nNode Name =" + tempNode.getNodeName() + " [OPEN]");
            System.out.println("Node Value =" + tempNode.getTextContent());

            if(tempNode.getNodeName()!=parent){





                System.out.println("----------------------------");



                if (tempNode.getChildNodes().getLength()>1){
                    NodeList nodeMap=tempNode.getChildNodes();
                    System.out.println("inside del");

                    for (int i=0;i<nodeMap.getLength();i++){



                        String e = "'"+(String)nodeMap.item(i).getNodeName()+"'";

                        System.out.println("inside del node:"+e);
                        NodeList nList = doc.getElementsByTagName(e);

                        if (nList.getLength()>1){

                            for (int con=1;i==nList.getLength()-1;con++){

                                Element el = (Element)nList.item(con);
                                System.out.println("element"+el);
                                System.out.println("parent"+el.getParentNode());
                                el.getParentNode().removeChild(el);
                            }
                            TransformerFactory transformerFactory = TransformerFactory.newInstance();

                            Transformer transformer = transformerFactory.newTransformer();
                            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                            DOMSource source = new DOMSource(doc);
                            StreamResult result = new StreamResult(new File(file));
                            transformer.transform(source, result);
                        }
                    }}}

            if (tempNode.hasChildNodes()) {

                // loop again if has child nodes
                printNote(doc, tempNode.getChildNodes());

            }

            System.out.println("Node Name =" + tempNode.getNodeName() + " [CLOSE]");

        }

    }

}}

【问题讨论】:

  • 在上面的标签中,我试图删除 标签中的 标签。
  • 请编辑您的问题,而不是添加 cmets。

标签: java xml parsing jakarta-ee xml-parsing


【解决方案1】:

问题似乎出在您试图删除节点的“for 循环”中。您的循环说:“for (int con=1;i==nList.getLength()-1;con++){” ...根据您的代码,打破循环的条件“i==nList.getLength( )-1" 始终为真,因此它永远不会进入该块...

我相信,这就是你应该做的(仍然觉得做一件很小的工作有点令人费解;但我猜你只是分享谜题的一部分......见下文;这将删除节点...

                        for (int con=nList.getLength()-1; con>=0; con--) {
                            Element el = (Element)nList.item(con);
                            System.out.println("element"+el);
                            System.out.println("parent"+el.getParentNode());
                            el.getParentNode().removeChild(el);
                        }
                        /*
                        for (int con=1;i==nList.getLength()-1;con++){

                            Element el = (Element)nList.item(con);
                            System.out.println("element"+el);
                            System.out.println("parent"+el.getParentNode());
                            el.getParentNode().removeChild(el);
                        }
                        */

希望这会有所帮助。

【讨论】:

  • 没有。在 NodeList nList = doc.getElementsByTagName(e);这里 e='test'..
  • 而不是标签名称,我使用这个: if (tempNode.getChildNodes().getLength()>1){ NodeList nList=tempNode.getChildNodes(); for (int con = nList.getLength()-1; con>0; con--){ } 这里 nList.getLength() 返回 7.. 它打印这个:**element[#text: ** ]跨度>
  • 首先,“get null”是指程序抛出 NullPointerException 吗?因为它不是为我做的。你能分享你的确切代码吗?还有你用的是什么版本的Java?
  • 我已经改了。 tnx ..现在没问题了..较新的问题是——“如果我必须删除除一个之外的所有节点,具有相同的标签名称和属性值怎么办?像 这里我要删除一个完整的节点 当属性和节点名都一样的时候?"
【解决方案2】:

使用 Xpath:

    Document doc = ...
    XPath xp = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xp.evaluate("//sai/test | //dinesh/test", doc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); ++i) {
        Node node = nodes.item(i);
        node.getParentNode().removeChild(node);
    }

    TransformerFactory tf ....

更新:

上面的代码只是你可以做的一个例子:另一种方法是找到所有具有多个 子节点的元素节点,然后做一些进一步的处理以删除重复项:

    NodeList nodes = (NodeList) xp.evaluate("//node()[count(./test) > 1", doc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); ++i) {
        Node parent= nodes.item(i);
        checkAndRemoveDuplicates(parent);
    }

关键在于 XPath 是一个强大的工具,可以帮助您用更少的代码解决问题。

【讨论】:

  • 这里我应该检查是否有多个同名节点...然后必须删除所有副本,除了一个。
  • 随心所欲。
  • 如果我必须删除除一个之外的所有具有相同标签名称和属性值的节点怎么办?比如 这里我要删除一个完整的节点 当属性和节点名都一样的时候?
【解决方案3】:

看起来像你打电话的时候

doc.getElementsByTagName(e);

e 的值类似于“'test'”。然而,XML 中的元素名称本身只是“测试”(没有单引号)。这可能是你的罪魁祸首

【讨论】:

  • 后来我只加了单引号。我也试过了。它仍然返回 null。
猜你喜欢
  • 2015-05-08
  • 2015-07-28
  • 2022-06-25
  • 1970-01-01
  • 2021-12-31
  • 2012-01-02
  • 2010-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多