【问题标题】:Unable to do the add, delete nodes in DOM XML document无法在 DOM XML 文档中添加、删除节点
【发布时间】:2015-04-14 13:37:29
【问题描述】:

实际上我正在为下面的 xml 字符串开发 XML DOM 解析器

<?xml version="1.0" encoding="UTF-8"?>
<schema version="1.0">
  <itemGroups>
    <itemGroup id="itemGroup1">
      <items>
        <item id="One" />
        <item id="Two" />
        <item id="item1" />
        <item id="item1" />
        <item id="item1" />
        <item id="item1" />
      </items>
    </itemGroup>
    <itemGroup id="itemGroup2">
      <items>
        <item id="One" />
        <item id="Two" />
        <item id="item1" />
        <item id="item1" />
        <item id="item1" />
        <item id="item1" />
      </items>
    </itemGroup>
  </itemGroups> 
</schema>

在这里,我需要从每个 itemGroup 中删除 ID 为“item”的项目。请帮助我只使用 Document 对象来做这件事。

这是我们用来删除元素但出现空指针异常的代码

public static Document removeElement(Document doc, String idValue,
            String groupNode, String itemNode) {
        NodeList itemGroupList = doc.getElementsByTagName(groupNode);
        for (int i = 0; i < itemGroupList.getLength(); i++) {
            Element node = (Element) itemGroupList.item(i);
            if (node.getAttribute("id").equals(idValue)) {
                NodeList itemlist = node.getElementsByTagName(itemNode);
                for (int j = 0; j < itemlist.getLength(); j++) {
                    Element nodenewitm = (Element) itemlist.item(j);
                    NodeList nodeListRemove = nodenewitm.getElementsByTagName("item");
                    if(nodenewitm != null) {
                        NodeList itemsList = nodenewitm.getChildNodes();
                        if(itemsList != null) {
                            for (int counter = 0; counter < itemsList.getLength(); counter++) {
                                Element item = (Element) itemlist.item(counter);
                                if(item.getAttribute("id").indexOf("ATTR_") > 0) {
                                    nodenewitm.removeChild(item);
                                }
                            }
                        }
                    }
                }
            }
        }
        return doc;
    }

我们只是调用 removeElement(document, "itemGroup1", "itemGroup", "items");

如果我能尽快得到帮助,我将不胜感激。

谢谢 拉梅什·雷迪

【问题讨论】:

    标签: xml xml-parsing


    【解决方案1】:

    改用 XPath。您可以根据需要构造表达式。

    void removeElement(Document doc)
            throws XPathExpressionException {
        XPath xp = XPathFactory.newInstance().newXPath();
    
        NodeList nl = (NodeList) xp.evaluate(
                "//items/item[starts-with(@id, 'item')]", doc,
                XPathConstants.NODESET);
        for (int i = 0; i < nl.getLength(); ++i) {
            nl.item(i).getParentNode().removeChild(nl.item(i));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-05
      • 2020-01-15
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      相关资源
      最近更新 更多