按名称删除xml节点并进行更新

时间:2012-11-27 09:33:06

标签: java xml nodes

我有一个以下的xml文件。

<abc>
  <sample name="xyz">
    <a>....</a>
  </sample>
  <sample name="pqr">
    <a>....</a>
  </sample>
</abc>    

我只需要删除<sample name="xyz">但是当我点击删除按钮时它会删除所有<sample>节点,但我只需要删除名称为“xyz”的节点。删除后我需要自动更新我的xml文件 这是我使用的代码,但不适合我

try{
   String xmlFile = "C:/practise.xml";
   File file = new File(xmlFile);
    String remElement = "sample";
   if (file.exists()){
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder = factory.newDocumentBuilder();
   Document doc = builder.parse(xmlFile);
   TransformerFactory tFactory = TransformerFactory.newInstance();
   Transformer tFormer = tFactory.newTransformer();
   Element element = (Element)doc.getElementsByTagName(remElement).item(0); 
   element.getParentNode().removeChild(element);
    doc.normalize();
    Source source = new DOMSource(doc);
   Result dest = new StreamResult(System.out);
   tFormer.transform(source, dest);
   System.out.println("jhala re delete");
   //createOutputFile("C:/MyTestbeds/TestBed1.xml", transformToString(doc));
}
else{
     System.out.println("File not found!");
   }
}
catch (Exception e){
System.err.println(e);

}
}

我不明白我的代码中有什么问题。我删除第一个节点时还需要更新我的xml文件。

1 个答案:

答案 0 :(得分:1)

适合我。尝试发布说明您问题的SSCCE

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class TestXML {

    private static final String XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<abc>\r\n" + "<sample name=\"xyz\">\r\n"
            + "    <a>....</a>\r\n" + "  </sample>\r\n" + "  <sample name=\"pqr\">\r\n" + "    <a>....</a>\r\n" + "  </sample>\r\n"
            + "</abc>";

    public static void main(String[] args) {
        try {
            String remElement = "sample";
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new ByteArrayInputStream(XML.getBytes("UTF-8")));
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer tFormer = tFactory.newTransformer();
            Element element = (Element) doc.getElementsByTagName(remElement).item(0);
            element.getParentNode().removeChild(element);
            doc.normalize();
            Source source = new DOMSource(doc);
            Result dest = new StreamResult(System.out);
            tFormer.transform(source, dest);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
}