我对Stax还是很陌生,目前尝试读取包含产品的大XML文件,并将使用matnr
属性将不同的产品文件写入不同的目录,目前我确实可以写很多文档,但是我应该用XML文件的静态字段丰富我的内容,我的文件内容是:
<?xml version="1.0" encoding="UTF-8" ?>
<CMD>
<DOCUMENT_NUMBER>0363244</DOCUMENT_NUMBER>
<CREATE_TIME>20181106T125340</CREATE_TIME>
<PRODUCT matnr="material1" change_type="I">
<TABLE name="table1">
...
</TABLE>
<TABLE name="table2">
....
</TABLE>
</PRODUCT>
<PRODUCT matnr="material2" change_type="I">
<TABLE name="table1">
...
</TABLE>
<TABLE name="table2">
....
</TABLE>
</PRODUCT>
</CMD>
我正在编写文件的代码:
import java.io.File;
import java.io.FileReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
public class Demo {
public static String elementString = "";
public static String staticString = "";
public static void main(String[] args) throws Exception {
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
while(xsr.hasNext()) {
int parseEvent = xsr.next();
if (parseEvent == XMLStreamConstants.START_ELEMENT && "PRODUCT".equals(xsr.getLocalName())) {
File file = new File("/xslt/templates/cmd-input-split/" + xsr.getAttributeValue(null, "matnr") + ".xml");
//System.out.println(cmdStr + staticString + new StAXSource(xsr) + cmdEndStr);
t.transform(new StAXSource(xsr), new StreamResult(file));
}
}
}
当前写入的文件的开头是类似下面的元素
<?xml version="1.0" encoding="UTF-8" ?>
<PRODUCT matnr="material1" change_type="I">
<TABLE name="table1">
...
</TABLE>
<TABLE name="table2">
....
</TABLE>
</PRODUCT>
但是我需要做的是添加输入中存在的一些元素,我应该读取文件的两个静态元素CREATE_TIME和DOCUMENT_NUMBER,并将这些值附加到通过转换器创建的每个文件中,最后我想给定xml中的两个文件是这样的:
material1.xml
<CMD>
<DOCUMENT_NUMBER>0363244</DOCUMENT_NUMBER>
<CREATE_TIME>20181106T125340</CREATE_TIME>
<PRODUCT matnr="material1" change_type="I">
<TABLE name="table1">
...
</TABLE>
<TABLE name="table2">
....
</TABLE>
</PRODUCT>
</CMD>
material2.xml
<CMD>
<DOCUMENT_NUMBER>0363244</DOCUMENT_NUMBER>
<CREATE_TIME>20181106T125340</CREATE_TIME>
<PRODUCT matnr="material2" change_type="I">
<TABLE name="table1">
...
</TABLE>
<TABLE name="table2">
....
</TABLE>
</PRODUCT>
</CMD>
我如何通过编辑实现来达到我的目标,有人可以支持吗?