使用java删除基于节点号的xml节点?

时间:2014-12-26 11:44:56

标签: java xml dom xml-parsing xmlnode

这里我的xml结构为

<book>  <!--node 0-->
    <id>1111</id>
    <name>abacd</name>
    <author>abcd</author>
    <price>700</price>
    <category>abcd</category>       
</book>                       
<book>  <!--node 1-->
    <id>2222</id>
    <name>abacd</name>
    <author>abcd</author>
    <price>700</price>
    <category>abcd</category>       
</book>  
<book>  <!--node 2-->
    <id>3333</id>
    <name>abacd</name>
    <author>abcd</author>
    <price>700</price>
    <category>abcd</category>       
</book>  

根据节点编号,我需要完全删除该节点。 我能够获得节点号和所有子节点,但我不知道如何deltet,任何人都可以指导我如何做它.Eg:node 0必须删除。 这就是我试图删除节点0:

File fXmlFile = new File(xmlfilePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    NodeList nList = doc.getElementsByTagName("book");
    Node nNode = nList.item(Integer.parseInt(nodeNumber));
    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
         Element eElement = (Element) nNode;
        String id = eElement.getElementsByTagName("id").item(0).getTextContent();
         if ((id.equals(bookId))) {
            eElement.getElementsByTagName("id").item(0).removeChild(nNode);
        }
    }

请帮助我获得所需的输出。

1 个答案:

答案 0 :(得分:0)

您的XML缺少根元素。这是我的更正版本:

<root>
<book>  <!--node 0 -->
    <id>1111</id>
    <name>abacd</name>
    <author>abcd</author>
    <price>700</price>
    <category>abcd</category>
</book>
<book>  <!--node 1 -->
    <id>2222</id>
    <name>abacd</name>
    <author>abcd</author>
    <price>700</price>
    <category>abcd</category>
</book>
<book>  <!--node 2 -->
    <id>3333</id>
    <name>abacd</name>
    <author>abcd</author>
    <price>700</price>
    <category>abcd</category>
</book>

这是使用XMLBeam

的JUnit测试
public class DeleteNodeTest {

public interface Books {
    @XBDelete("//book[id=$PARAM0]")
    int deleteBooks(int id);
}

@Test
public void deleteNode() throws IOException {
    Books books = new XBProjector(Flags.TO_STRING_RENDERS_XML).io().url("resource://test.xml").read(Books.class);
    System.out.println("Deleted " + books.deleteBooks(1111) + " nodes.");
    System.out.println(books);
}

}

此程序打印出来:

Deleted 1 nodes.

<book>  <!--node 1 -->
    <id>2222</id>
    <name>abacd</name>
    <author>abcd</author>
    <price>700</price>
    <category>abcd</category>
</book>
<book>  <!--node 2 -->
    <id>3333</id>
    <name>abacd</name>
    <author>abcd</author>
    <price>700</price>
    <category>abcd</category>
</book>