我很震惊这个代码我有一个巨大的xml文件,其中包含各种"服务器"," port"需要更新的标签。当我执行下面的代码时,只有first.server和端口号得到更新,它不会循环遍历整个代码并更改所有端口和服务器标签我没有收到任何错误但无法遍历代码:
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();
}
}
}
答案 0 :(得分:1)
在Node employee = document.getElementsByTagName("connection").item(0);
行上,您只获得一个节点。
如果您改为
NodeList employees = document.getElementsByTagName("connection");
for(int i = 0; i < employees.getLength(); i++) {
Node employee = employees.item(i);
....
}
你应该迭代它们。