gpt4 book ai didi

java - XML 文件没有循环通过 Out

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

我对这段代码感到震惊,我有一个巨大的 xml 文件,其中包含需要更新的各种“服务器”、“端口”标签。当我执行下面的代码时,只有第一个服务器和端口号得到更新,它不会循环遍历整个代码并更改所有端口和服务器标记,我没有收到任何错误,但无法循环遍历代码:

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class XMLFile {
public static final String xmlFilePath ="C:\\Users\\c200433\\Desktop\\Kommu234.twb";
public static void main(String argv[]) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(xmlFilePath);
Node employee = document.getElementsByTagName("connection").item(0);
NamedNodeMap attribute = employee.getAttributes();
Node nodeAttr = attribute.getNamedItem("server");
nodeAttr.setTextContent("aventador.a:1530");
Node nodeAttr1 = attribute.getNamedItem("service");
Node nodeAttr2 = attribute.getNamedItem("port");
nodeAttr1.setTextContent("tst806");
nodeAttr2.setTextContent(""); // Value is correct but doesnt get looped through
TransformerFactory transformerFactory = TransformerFactory.newInstance();

Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);

StreamResult streamResult = new StreamResult(new File(xmlFilePath)); transformer.transform(domSource, streamResult);

System.out.println("The XML File was ");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
}

最佳答案

NodeEmployee = document.getElementsByTagName("connection").item(0); 行上,您仅获得一个节点。

如果你这样做

NodeList employees = document.getElementsByTagName("connection");
for(int i = 0; i < employees.getLength(); i++) {
Node employee = employees.item(i);
....
}

您应该迭代它们。

关于java - XML 文件没有循环通过 Out,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25749492/

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