Insert new element to an XML file using SAX Filter

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

I have an XMl file that looks like:



  
    2
    

        
3条回答
  •  攒了一身酷
    2021-01-20 01:55

    Your XMLFilter should delegate to another ContentHandler that serializes the document based on the sax events.

    SAXTransformerFactory factory = (SAXTransformerFactory)TransformerFactory.newInstance();
    TransformerHandler serializer = factory.newTransformerHandler();
    Result result = new StreamResult(...);
    serializer.setResult(result);
    
    XMLFilterImpl filter = new MyFilter();
    filter.setContentHandler(serializer);
    
    XMLReader xmlreader = XMLReaderFactory.createXMLReader();
    xmlreader.setFeature("http://xml.org/sax/features/namespaces", true);
    xmlreader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    xmlreader.setContentHandler(filter);
    
    xmlreader.parse(new InputSource(...));
    

    Your callback should delegate to the super implementation, which forwards the events to the serializing ContentHandler.

    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        super.startElement(namespaceURI, localName, qName, atts);
        ...
    }
    

    In your endElement callback you can check if your are at the final closing tag and add additional sax events.

    public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
        super.endElement(namespaceURI, localName, qName);
        if ("game".equals(localName)) {
            super.startElement("", "statistics", "statistics", new AttributesImpl());
            char[] chars = String.valueOf(num).toCharArray();
            super.characters(chars, 0, chars.length);
            super.endElement("", "statistics", "statistics");
        }
        ...
    }
    

提交回复
热议问题