Java XML RemoveChild的问题

时间:2011-05-18 13:10:32

标签: java xml

我有以下代码:

try {
    Builder builder = new Builder();
    Document doc = builder.build(Config.PATH +"incasation.xml");

    Element root = doc.getRootElement();    
    Elements childs = root.getChildElements("locations");

    int nodeToDelete = 0;
    for(int i=0; i < childs.size(); i++)
    {
        Element child = childs.get(i);
        System.out.print(child.getFirstChildElement("name").getValue());
        System.out.print(" - ");
        System.out.print(getLocationName().getText());
        System.out.print(" - ");
        System.out.println(child.getFirstChildElement("name").getValue().equals(getLocationName().getText()));

        if(child.getFirstChildElement("name").getValue().equals(getLocationName().getText()))
        {
            nodeToDelete = i;
        }
    }

    root.removeChild(nodeToDelete);
    Simplexml sx = new Simplexml();
    sx.save(root, Config.PATH +"incasation.xml");
}
catch(Exception e) {}

我的问题是:

为什么removeChild(i)无效?

编辑: 一周后我找到了解决办法:)

root.removeChild(nodeToDelete);         
Element root2 = (Element) root.copy();

Simplexml sx = new Simplexml();
sx.save(root2, Config.PATH +"incasation.xml");

Java appending XML docs to existing docs

1 个答案:

答案 0 :(得分:0)

编译时间错误? org.w3c.dom.Element#removeChild期望Node对象而不是整数值。或者您使用名为Element的其他类?