【发布时间】:2015-09-17 22:59:50
【问题描述】:
我有一个 XML 文件 (client_23.xml),如下所示。我有一个字符串变量out,我需要在XML 下方插入一个特定位置。这不是我的完整 XML,因为我有很多其他嵌套的东西,函数标签将在其中,并且不一致,因为这个 XML 是通过代码生成的,所以我需要
<?xml version="1.0"?>
<clients>
<!-- some other code here -->
<function>
</function>
<function>
</function>
<function>
<name>data_values</name>
<variables>
<variable>
<name>temp</name>
<type>double</type>
</variable>
</variables>
<block>
<opster>temp = 1</opster>
</block>
</function>
</clients>
我需要解析上面的XML,找到一个名为data_values的函数,然后在<block>标签中插入out字符串变量。这不是我的完整 XML,因为我有很多其他嵌套的东西,函数标签将在其中,并且它不一致,因为这个 XML 是通过代码生成的,所以我需要解析和迭代并找到它,然后放它。
所以最终的 xml 将如下所示:
<?xml version="1.0"?>
<clients>
<!-- some other code here -->
<function>
</function>
<function>
</function>
<function>
<name>data_values</name>
<variables>
<variable>
<name>temp</name>
<type>double</type>
</variable>
</variables>
<block>
<!-- new stuff added and old things were gone -->
<opster>hello = world</opster>
<opster>abc = def</opster>
</block>
</function>
</clients>
以下是我得到的代码,但我无法理解如何在块标记中的data_values 函数中放入变量。
StringBuilder out = new StringBuilder();
// some data in out variable, properly formatted with new lines.
String location = key.getPathName();
String clientIdPath = location + "/" + "client_23.xml";
File fileName = new File(clientIdPath);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(fileName);
NodeList dataValueFunction = document.getElementsByTagName("function");
// I have started iterating but I am not able to understand how to insert "out"
// variable inside block
for (int i = 0; i < dataValueFunction.getLength(); i++) {
Node node = dataValueFunction.item(i);
System.out.println(node.getNodeName());
NodeList childList = node.getChildNodes();
for (int j = 0; j < childList.getLength(); j++) {
Node node1 = childList.item(j);
if (node1 != null && node1.getNodeName().equalsIgnoreCase("name")
&& node1.getTextContent().equalsIgnoreCase("data_values")) {
// now what should I do here?
}
}
}
【问题讨论】: