0

我有一个以下 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 文件。

4

1 回答 1

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();

        }
    }
}
于 2012-11-27T09:53:37.667 回答