e544. removing a node from a dom document.txt
来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 65 行
TXT
65 行
This example demonstrates how to remove a single node and all nodes of a particular type.
// Obtain an XML document; this method is implemented in
// e510 The Quintessential Program to Create a DOM Document from an XML File
Document doc = parseXmlFile("infilename.xml", false);
// Obtain a node
Element element = (Element)doc.getElementsByTagName("junk").item(0);
// Remove the node
element.getParentNode().removeChild(element);
// Remove all <junk> elements
removeAll(doc, Node.ELEMENT_NODE, "junk");
// Remove all comment nodes
removeAll(doc, Node.COMMENT_NODE, null);
// Normalize the DOM tree to combine all adjacent text nodes
doc.normalize();
// This method walks the document and removes all nodes
// of the specified type and specified name.
// If name is null, then the node is removed if the type matches.
public static void removeAll(Node node, short nodeType, String name) {
if (node.getNodeType() == nodeType &&
(name == null || node.getNodeName().equals(name))) {
node.getParentNode().removeChild(node);
} else {
// Visit the children
NodeList list = node.getChildNodes();
for (int i=0; i<list.getLength(); i++) {
removeAll(list.item(i), nodeType, name);
}
}
}
This is the sample input for the example:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<!--comment1-->
<elem>a</elem>
<junk>b</junk>
<elem>
<!--comment2-->
<junk>c<junk>d</junk></junk>
</elem>
<!--comment3-->
<junk>e</junk>
</root>
This is the resulting XML:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<elem>a</elem>
<elem>
</elem>
</root>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?