user3119134
user3119134

Reputation: 157

XML processing using SAX or STAX

I am new to JAVA programming and Parsers to process XML files, now I in need of JAVA program to read a big XML file that containing .. tags. Sample input as follows.

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>

New `Input.xml`:

    <row>
    <Name>Filename1</Name>
    </row>
    <row>
    <Name>Filename2</Name>
    </row>
    <row>
    <Name>Filename3</Name>
    </row>

I need output as first <row> </row> as a single .xml file with filename as filename1.xml and second <row>..</row> as filename2.xml and so.

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>

It gives output as 1.xml,2.xml...but now my aim is different my file name should be the content inside tag .

Should i modify the source code to get outcome og my new aim.If it is possible can you send the modified source code??? I used STAX parser

Can you please guide us?

Thanks,

Sowmiya

Upvotes: 1

Views: 929

Answers (1)

Basilevs
Basilevs

Reputation: 23916

Replace

xsr.getAttributeValue(null,"id")

with

xsr.getElementText()

Upvotes: 1

Related Questions