Insert new element to an XML file using SAX Filter

前端 未结 3 630
逝去的感伤
逝去的感伤 2021-01-20 01:22

I have an XMl file that looks like:



  
    2
    

        
3条回答
  •  不要未来只要你来
    2021-01-20 01:34

    Using @Jorn Horstmann's (http://stackoverflow.com/users/139595/jorn-horstmann) answer from above you can easily add the missing elements. But to write the results to an XML file you should use the TransformerHandler.

    Just create a very basic ContentHandler and use it instead of the DefaultHandler. In the ContentHandler you can implement all the basic functions (startDocument, startElement etc.) and add every element to a new Transformer. e.g. In your startDocument function:

    Transformer t = hd.getTransformer();
    t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    t.setOutputProperty(OutputKeys.METHOD, "xml");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    hd.startDocument();
    

    And then (in each other function) add this: e.g. for startElement:

    hd.startElement(uri,localName,name,attributes);
    

    Finally you can write all this to a file in the endDocument method.

提交回复
热议问题