我是这个主题的新手,但我阅读了很多有关该主题的解决方案。不幸的是,他们都是在一个非常简单的情况下,我无法重新调整我的问题。我的 XML 文档的结构如下:
<messagge>
<heading>
<context>
<forniture>
<fornitureHeading>..other tags..</fornitureHeading>
<document>
...other tags...
</document>
<document>
...
</document>
...
</forniture>
</context>
</heading>
</messagge>
我需要为每个 <document>
创建一个新的 XML 文件但我需要维护上面的所有信息(标签 - 属性 - 等等),如下所示:
document1.xml
<messagge>
<heading>
<context>
<forniture>
<fornitureHeading>..other tags..</fornitureHeading>
<document1>
...other tags...
</document1>
</forniture>
</context>
</heading>
</messagge>
document2.xml
<messagge>
<heading>
<context>
<forniture>
<fornitureHeading>..other tags..</fornitureHeading>
<document2>
...other tags...
</document2>
</forniture>
</context>
</heading>
</messagge>
所以.... 我尝试过这个脚本 https://stackoverflow.com/a/2057161/3116904
File input = new File(pathFile);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = dbf.newDocumentBuilder().parse(input);
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xpath.evaluate("//Message/Context/Forniture/Document", doc, XPathConstants.NODESET);
int itemsPerFile = 1;
int fileNumber = 0;
Document currentDoc = dbf.newDocumentBuilder().newDocument();
Node rootNode = currentDoc.createElement("Message");
File currentFile = new File(OUTPUT_FOLDER+fileNumber+".xml");
for (int i=1; i <= nodes.getLength(); i++) {
Node imported = currentDoc.importNode(nodes.item(i-1), true);
rootNode.appendChild(imported);
if (i % itemsPerFile == 0) {
writeToFile(rootNode, currentFile);
rootNode = currentDoc.createElement("Messaggio");
currentFile = new File(OUTPUT_FOLDER+(++fileNumber)+".xml");
}
}
此脚本的问题是它在新文件中仅写入 <document>
标签,而不是父标签。
现在很清楚并且等于链接的节点,但我尝试了一些解决方案来写入上层节点,将它们添加到 NodeList 中,然后尝试在每个 <document>
处附加此节点节点,但没有工作。
任何建议都会受到重视。
谢谢
其他信息:
-我无法更改 XML 结构
-我需要保持相同的结构(<document1><document2>
只是为了更好地解释我的情况)
最佳答案
您预计您的文档有多大? 您是否可以控制 xml,例如可以更改其结构吗? 它在语义上看起来不正确(标题中的文档?)
而通过分割文件,你还期望维持之前的xml结构吗? <document1>, <document2>,
听起来不对。
或者您拆分文件的目的是什么
无论哪种方式都可以,这只是进一步的信息,可以帮助人们为您提供更好的解决方案。
关于java - 使用 Java 拆分 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29164214/