stax - get xml node as string

后端 未结 5 1495
孤街浪徒
孤街浪徒 2021-01-05 15:49

xml looks like so:


   
      ...stuff...
   
   
              


        
5条回答
  •  盖世英雄少女心
    2021-01-05 16:27

    You can use StAX for this. You just need to advance the XMLStreamReader to the start element for statement. Check the account attribute to get the file name. Then use the javax.xml.transform APIs to transform the StAXSource to a StreamResult wrapping a File. This will advance the XMLStreamReader and then just repeat this process.

    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 Demo {
    
        public static void main(String[] args) throws Exception  {
            XMLInputFactory xif = XMLInputFactory.newInstance();
            XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
            xsr.nextTag(); // Advance to statements element
    
            while(xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer t = tf.newTransformer();
                File file = new File("out" + xsr.getAttributeValue(null, "account") + ".xml");
                t.transform(new StAXSource(xsr), new StreamResult(file));
            }
        }
    
    }
    

提交回复
热议问题