//**在 NodeList nList = doc.getElementsByTagName(e); 下面是我的 xml 内容我正在尝试删除 xml 文件中存在的类似标签。nList 显示为空。如何解决问题?
**
public class DelElement {
public static String parent;
public static void main(String[] args) {
try {
File file = new File("D:/vodafone/parse.xml");
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = dBuilder.parse(file);
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
parent=doc.getDocumentElement().getNodeName();
if (doc.hasChildNodes()) {
printNote(doc,doc.getChildNodes());
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static void printNote(Document doc, NodeList nodeList) throws TransformerException {
String file = "D:/vodafone/parse.xml";
for (int count = 0; count < nodeList.getLength(); count++) {
Node tempNode = nodeList.item(count);
// make sure it's element node.
if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
// get node name and value
System.out.println("\nNode Name =" + tempNode.getNodeName() + " [OPEN]");
System.out.println("Node Value =" + tempNode.getTextContent());
if(tempNode.getNodeName()!=parent){
System.out.println("----------------------------");
if (tempNode.getChildNodes().getLength()>1){
NodeList nodeMap=tempNode.getChildNodes();
System.out.println("inside del");
for (int i=0;i<nodeMap.getLength();i++){
String e = "'"+(String)nodeMap.item(i).getNodeName()+"'";
System.out.println("inside del node:"+e);
NodeList nList = doc.getElementsByTagName(e);
if (nList.getLength()>1){
for (int con=1;i==nList.getLength()-1;con++){
Element el = (Element)nList.item(con);
System.out.println("element"+el);
System.out.println("parent"+el.getParentNode());
el.getParentNode().removeChild(el);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(file));
transformer.transform(source, result);
}
}}}
if (tempNode.hasChildNodes()) {
// loop again if has child nodes
printNote(doc, tempNode.getChildNodes());
}
System.out.println("Node Name =" + tempNode.getNodeName() + " [CLOSE]");
}
}
}}