gpt4 book ai didi

java - 按名称删除 xml 节点并更新它

转载 作者:行者123 更新时间:2023-12-01 15:01:29 26 4
gpt4 key购买 nike

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

最佳答案

对我有用。尝试发布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();

}
}
}

关于java - 按名称删除 xml 节点并更新它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13581159/

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