gpt4 book ai didi

java - 从 XML 文件中删除元素 Java

转载 作者:行者123 更新时间:2023-11-30 06:42:13 25 4
gpt4 key购买 nike

我有一个 xml 文件,其中包含以下内容:

<class>
<Video>Spiderman</Video>
<Video>Superman</Video>
</class>

我想根据用户输入的内容删除其中一个。到目前为止我所拥有的是

for (int x=0; x<videodatabase.size(); x++) {
if (inputVideo.getText().contentEquals(videodatabase.get(x))) {
try {
String filepath = "videodatabase.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);

// I want to remove the <Video>name of the video</Video> from the xml here.

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
}
catch(ParserConfigurationException pce){
pce.printStackTrace();
}
catch(TransformerException tfe){
tfe.printStackTrace();
}
catch(IOException ioe){
ioe.printStackTrace();
}
catch(SAXException sae){
sae.printStackTrace();
}
}
}

正如您所看到的,程序检查输入的视频名称是否在名为 videodatabase 的数组列表中。如果是,则打开 xml 文件并准备删除输入的视频。然而我被困在这里了。我希望 xml 文件看起来像:

<class>
<Video>Spiderman</Video>
</class>

最佳答案

这是使用 XPath 时缺少的部分:

// Get a XPath instance
XPath xpath = XPathFactory.newInstance().newXPath();
// Find the Video element with text 'Superman'
Element supermanVideo = (Element) xpath.evaluate("/class/Video[. = 'Superman']",
doc, XPathConstants.NODE);
if(supermanVideo != null) {
// Remove this element from the parent
supermanVideo.getParentNode().removeChild(supermanVideo);
}
// Serialize the XML document ...

关于java - 从 XML 文件中删除元素 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44218960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com