gpt4 book ai didi

Java 从 XML 文件中删除子项

转载 作者:行者123 更新时间:2023-12-01 13:13:33 25 4
gpt4 key购买 nike

我想从 XML 文件中删除一个子文件,当然还要在修改后保存该文件。这是我的 XML 文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Customers>
<Marker>
<title>ABB EMEA</title>
</Marker>
<Marker>
<title>AllScripts</title>
</Marker>
<Marker>
<title>ARRIS (Motorola)</title>
</Marker>
<Marker>
<title>ARRIS (RWC)</title>
</Marker>
<Marker>
<title>BHS</title>
<site_location>Weinhammer, Hofhalde, Konstanz, Germany</site_location>
</Marker>
<Marker>
<title>Durst</title>
<site_location>Brixen, Italy</site_location>
</Marker>
<Marker>
<title>EMEA DEMO</title>
<site_location>AWS could</site_location>
</Marker>
<Marker>
<title>Harris</title>
</Marker>

</Customers>

我想完全删除具有“title”-“Durst”的子项。

这是我的代码:

public static void Rebuild_Cords_XML (File ff)
{
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(ff);

NodeList nodes = doc.getElementsByTagName("Marker");
int x=0;
for(int i=0;i<nodes.getLength();i++)
{
Node nNode = nodes.item(i);

if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;
if(eElement.getElementsByTagName("title").item(0).getTextContent().equals(("Durst")));
{

}
}
}


// write the DOM object to the file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer=null;
try {
transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DOMSource domSource = new DOMSource(doc);
StreamResult streamResult = new StreamResult(ff);
try {
transformer.transform(domSource, streamResult);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
catch (ParserConfigurationException | IOException | SAXException e) {
;}
}

正如您所看到的,我能够手动检测到它,但我不知道要删除它,尝试访问父节点会删除其他“标记”子节点,但不会删除所需的节点。

请帮忙。

最佳答案

我不完全确定您要删除的内容,因此有两种方法。

这将删除包含标题 durst 的整个标记:

        for (int i = 0; i < nodes.getLength(); i++) {
Node nNode = nodes.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if (eElement.getElementsByTagName("title").item(0).getTextContent().equals(("Durst"))) {
nNode.getParentNode().removeChild(nNode);
}
}
}

这将仅删除标记中的标题标签:

        for (int i = 0; i < nodes.getLength(); i++) {
Node nNode = nodes.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if (eElement.getElementsByTagName("title").item(0).getTextContent().equals(("Durst"))) {
nNode.removeChild(eElement.getElementsByTagName("title").item(0));
}
}

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

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