Search code examples
javaparsingsaxchildrenelement

Children manipulation at SAX Parsing


Assuming i got an XML file which im SAX parsing(to Java) of the following format:

                <RootElement>
                  <text> blabla </text>
                  <rule1 name="a">1</rule1>
                  <rule2 name="b">2</rule2>
                </RootElement>

How can i refer to the attribute of name in every rule ? My aim is to save to a txt file only the rules with name "a" for example. Thank you


Solution

  • When you read XML with a SAX Parser you implement a kind of ContentHandler (see http://docs.oracle.com/javase/7/docs/api/org/xml/sax/ContentHandler.html). Within your ContentHandler, the method startElement is called when the parser enters "rule1" and "rule2". One Parameter of startElement are the Attributes which is basically a map of attribute names ("name" in your example) to the correspondig values.

    Some code snippet would look like:

    // Handle XML SAX parser events.
    private ContentHandler contentHandler = new ContentHandler() {
        public void startDocument() throws SAXException {...}
    
        public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
            cdata.setLength(0);
            if(atts == null) return;            
            // Write out attributes as new rows
            for(int i = 0; i < atts.getLength(); i++) {
                System.out.println(atts.getLocalName(i) + ": " + atts.getValue(i));
            }
        }
    
    
        public void characters(char[] ch, int start, int length) throws SAXException {...}
    
        public void endElement(String uri, String localName, String qName) throws SAXException {...}
    
        // All other events are ignored
        public void endDocument() throws SAXException {}
        public void endPrefixMapping(String prefix) throws SAXException {}
        public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}
        public void processingInstruction(String target, String data) throws SAXException {}
        public void setDocumentLocator(Locator locator) {}
        public void skippedEntity(String name) throws SAXException {}
        public void startPrefixMapping(String prefix, String uri) throws SAXException {}
    };