我是JAVA编程和Parsers的新手来处理XML文件,现在我需要JAVA程序来读取包含..标签的大型XML文件。示例输入如下。
我以前的xml文件是。
<employees>
<Employee id="1">
<age>29</age>
<name>Pankaj</name>
<gender>Male</gender>
<role>Java Developer</role>
</Employee>
<Employee id="2">
<age>35</age>
<name>Lisa</name>
<gender>Female</gender>
<role>CEO</role>
</Employee>
</employee>
New `Input.xml`:
<row>
<Name>Filename1</Name>
</row>
<row>
<Name>Filename2</Name>
</row>
<row>
<Name>Filename3</Name>
</row>
我需要输出第一个<row> </row>
作为单个.xml
文件,文件名为filename1.xml
,第二个<row>..</row>
为filename2.xml
等等。
I have tried something like:
Using this code we can split the xml document which contains below format.But this code not supported by new aim that was mentioned in the above question.my source code is,
import java.io.File;
import java.io.FileReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
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 Big {
public static void main(String[] args) throws Exception {
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
xsr.nextTag();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
while(xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
File file = new File("output1/" + xsr.getAttributeValue(null,"id") + ".xml");
t.transform(new StAXSource(xsr), new StreamResult(file));
}
}
}
my previous xml file is .
<employees>
<Employee id="1">
<age>29</age>
<name>Pankaj</name>
<gender>Male</gender>
<role>Java Developer</role>
</Employee>
<Employee id="2">
<age>35</age>
<name>Lisa</name>
<gender>Female</gender>
<role>CEO</role>
</Employee>
</employee>
它输出为1.xml,2.xml ...但现在我的目标是不同的,我的文件名应该是标签内的内容。
我应该修改源代码以获得结果和我的新目标。如果有可能你可以发送修改后的源代码???我使用了STAX解析器
你能指导我们吗?
谢谢,
Sowmiya
答案 0 :(得分:1)
替换
xsr.getAttributeValue(null,"id")
与
xsr.getElementText()