繁体   English   中英

使用SAX或STAX的XML处理

[英]XML processing using SAX or STAX

我是JAVA编程和解析器处理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 ...,但是现在我的目标是不同的,我的文件名应该是tag内的内容。

我是否应该修改源代码以获得新的目标。如果可以,您可以发送修改后的源代码吗??? 我用了STAX解析器

你能指导我们吗?

谢谢,

Sowmiya

更换

xsr.getAttributeValue(null,"id")

xsr.getElementText()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM