如何使用Java DOM解析器查找Node属性值并将其删除

时间:2016-03-09 08:32:04

标签: java dom xml-parsing

如何查找和删除项目ID =" s2"使用Java DOM解析器?

<manifest>
    <item href="html/section1.html" id="s1" media-type="application/xhtml+xml"/>
    <item href="html/section2.html" id="s2" media-type="application/xhtml+xml"/>
    <item href="html/section3.html" id="s3" media-type="application/xhtml+xml"/>
</manifest>

我使用此代码但返回Null

Node metadataXML = doc.getElementsByTagName("manifest").item(0);
        NodeList list = metadataXML.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            list.item(i).getAttributes().removeNamedItem("s2");
        }

3 个答案:

答案 0 :(得分:1)

我发现this链接评论和工作中的差异方式

 NodeList nList = doc.getElementsByTagName("item");
        for (int i = 0; i < nList.getLength(); i++) {
            Node node = nList.item(i);
            if (node.getNodeType() == Element.ELEMENT_NODE) {
                Element eElement = (Element) node;
                System.out.println(eElement.getAttribute("id"));
                if (eElement.getAttribute("id").equals("s" + index)) {
                    System.err.println("sdsd");
                    node.getParentNode().removeChild(node);
                }
            }
        }

答案 1 :(得分:0)

看看这个答案:Removing DOM nodes when traversing a NodeList

你必须使用类似的东西:

Node metadataXML = doc.getElementsByTagName("manifest").item(0);
NodeList list = metadataXML.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {

    Element manifestItem = (Element) list.item(i);
    if ("s2".equals(manifestItem.getAttribute("id"))) {
        metadataXML.removeChild(manifestItem);
    }

}

答案 2 :(得分:0)

以下是在vtd-xml中执行此操作的代码,而不是DOM,您可以在SO上找到相当多的参考,甚至是它自己的标记......

import com.ximpleware.*;

public class deleteNode {
    public  static  void main(String s[]) throws VTDException,java.io.UnsupportedEncodingException,java.io.IOException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", false))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        XMLModifier xm = new XMLModifier(vn);
        ap.selectXPath("/*/*[@id='s2']");// this is the key XPath expression
        int i=0;
        while((i=ap.evalXPath())!=-1){

            xm.remove(vn.getElementFragment());// remove the node
        }
        xm.output("new.xml"); // output to a new document called new.xml
    }

}