我有一个 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
的函数然后插入out
<block>
中的字符串变量标签。这不是我的完整 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
中放入变量 block 标签中的函数。
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?
}
}
}
最佳答案
检查这个问题。您可以使用 XPath 表达式来定位正确的函数标记并使用 Xpath 更新它。
How to update XML using XPath and Java
这是一个快速代码。
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("data.xml"));
List<String> outs = Arrays.asList(new String[] { "hello = world", "abc = def" });
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
System.out.println("*************************");
String expression = "//clients/function/name[text()='data_values']";
System.out.println(expression);
Node nameTag = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
for (int i = 0; i < nameTag.getParentNode().getChildNodes().getLength(); i++) {
if (nameTag.getParentNode().getChildNodes().item(i).getNodeName().equals("block")) {
System.out.println("GOT BLOCK");
nameTag.getParentNode().removeChild(nameTag.getParentNode().getChildNodes().item(i));
Node node = xmlDocument.createElement("block");
nameTag.getParentNode().appendChild(node);
for (String out : outs) {
Node newNode = xmlDocument.createElement("opster");
newNode.setTextContent(out);
node.appendChild(newNode);
}
}
}
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(xmlDocument);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
关于java - 在 XML 文件中的特定位置插入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32641265/