我有以下xml文件作为输入….
xsi:schemaLocation="http://www.safersys.org/namespaces/T0020V1 T0020V1.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.safersys.org/namespaces/T0020V1">
SAFER
04.02
01.00
REPLACE
2009-09-01T00:00:00
CT
274845
US
AR
55002
I
100
2007-11-06
2009-08-03
LG
A P SUPPLY CO
PH
1400 N OATS
TEXARKANA
AR
71854
MILLER
US
MA
P O BOX 1927
TEXARKANA
AR
75504
US
.....
.....
.....
我想把这个xml文件通过像这样的java代码分成多个文件…
File1.xml
.....
.....
File2.xml
.....
.....
File3.xml
.....
.....
以及更多xml文件.每个xml文件包含最多10或15个IRP_ACCOUNT.
有人能帮帮我吗 ?
解决方法:
又快又脏:
public class XmlSplit {
public static void main(String [] args) throws Exception {
File input = new File("input.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = dbf.newDocumentBuilder().parse(input);
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xpath.evaluate("//T0020/IRP_ACCOUNT", doc, XPathConstants.NODESET);
int itemsPerFile = 5;
int fileNumber = 0;
Document currentDoc = dbf.newDocumentBuilder().newDocument();
Node rootNode = currentDoc.createElement("T0020");
File currentFile = new File(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("T0020");
currentFile = new File((++fileNumber)+".xml");
}
}
writeToFile(rootNode, currentFile);
}
private static void writeToFile(Node node, File file) throws Exception {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(node), new StreamResult(new FileWriter(file)));
}
}
标签:java,xml
来源: https://codeday.me/bug/20190927/1822872.html