1

How can I split an xml-string into different xml-strings by tag?

Suppose I have the following XML. How can I have a xml-string with tag1 and its values, tag2 and its values and, tag3 with its values.

 <?xml version="1.0"?>
 <Tag0>
   <Tag1> //Other tags and values for tag1 </Tag1>
   <Tag2> </Tag2>
   <Tag3> </Tag3>
 </Tag0>     

I'm splitting the XML because when I create the XSD for the xml-strings it creating just XSD for just the tag1 because rest of them have the same namespace as tag1.

1

3 Answers 3

3

After you parse the XML you can call the method getElementsByTagName this will return a NodeList, and just instantiate a Node object for each element from the NodeList.

Sign up to request clarification or add additional context in comments.

1 Comment

1

Use a SAXParser to parse the xml to Java object first. You can then get anything using it.

Comments

1

Here is the code to do the splitting in XPath and vtd-xml.

import com.ximpleware.*;
import java.io.*;
public class splitXML {
    public static void main(String[] args) throws VTDException, IOException {
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("d:\\xml\\input.xml", false)){
            System.out.println("error");
            return;
        }
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        ap.selectXPath("/tag0/*");
        int i=0,n=0;
        FileOutputStream fos =null;
        while((i=ap.evalXPath())!=-1){
            fos = new FileOutputStream("d:\\xml\\output"+(++n)+".xml");
            long l = vn.getElementFragment();
            fos.write(vn.getXML().getBytes(), (int)l, (int)(l>>32));
            fos.close();
        }
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.