Getting Parent Child Hierarchy in Sax XML parser

2019-01-29 07:55发布

I'm using SAX (Simple API for XML) to parse an XML document. I'm getting output for all the tags the file have, but i want it to show the tags in parent child hierarchy. For Example: This is my output

<dblp>
<www>
<author>
</author><title>
</title><url>
</url><year>
</year></www><inproceedings>
<month>
</month><pages>
</pages><booktitle>
</booktitle><note>
</note><cdrom>
</cdrom></inproceedings><article>
<journal>
</journal><volume>
</volume></article><ee>
</ee><book>
<publisher>
</publisher><isbn>
</isbn></book><incollection>
<crossref>
</crossref></incollection><editor>
</editor><series>
</series></dblp>

But i want it to display the output like this (it displays the children with extra spacing (that's how i want it to be))

<dblp>
  <www>
    <author>
    </author>
    <title>
    </title>
    <url>
    </url>
    <year>
    </year>
  </www>
  <inproceedings>
    <month>
    </month>
    <pages>
    </pages>
    <booktitle>
    </booktitle>
    <note>
    </note>
    <cdrom>
    </cdrom>
  </inproceedings>
  <article>
    <journal>
    </journal>
    <volume>
    </volume>
  </article>
  <ee>
  </ee>
  <book>
    <publisher>
    </publisher>
    <isbn>
    </isbn>
  </book>
  <incollection>
    <crossref>
    </crossref>
  </incollection>
  <editor>
  </editor>
  <series>
  </series>
</dblp>

But i can't figure out how can i detect that parser is parsing a parent tag or a children.

here is my code:

package com.teamincredibles.sax;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Parser extends DefaultHandler {

  public void getXml() {
    try {
      SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
      SAXParser saxParser = saxParserFactory.newSAXParser();
      final MySet openingTagList = new MySet();
      final MySet closingTagList = new MySet();
      DefaultHandler defaultHandler = new DefaultHandler() {

        public void startDocument() throws SAXException {
          System.out.println("Starting Parsing...\n");
        }

        public void endDocument() throws SAXException {
          System.out.print("\n\nDone Parsing!");
        }

        public void startElement(String uri, String localName, String qName,
          Attributes attributes) throws SAXException {
          if (!openingTagList.contains(qName)) {
            openingTagList.add(qName);
            System.out.print("<" + qName + ">\n");
          }
        }

        public void characters(char ch[], int start, int length)
        throws SAXException {
          /*for(int i=start; i<(start+length);i++){
            System.out.print(ch[i]);
        }*/
        }

        public void endElement(String uri, String localName, String qName)
        throws SAXException {
          if (!closingTagList.contains(qName)) {
            closingTagList.add(qName);
            System.out.print("</" + qName + ">");
          }
        }
      };

      saxParser.parse("xml/sample.xml", defaultHandler);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String args[]) {
    Parser readXml = new Parser();
    readXml.getXml();
  }
}

3条回答
Emotional °昔
2楼-- · 2019-01-29 08:16

You can consider a StAX implementation:

package be.duo.stax;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class StaxExample {

    public void getXml() {
        InputStream is = null;
        try {
            is = new FileInputStream("c:\\dev\\sample.xml");

            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
            XMLStreamReader reader = inputFactory.createXMLStreamReader(is);

            parse(reader, 0);

        } catch(Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
            if(is != null) {
                try {
                    is.close();
                } catch(IOException ioe) {
                    System.out.println(ioe.getMessage());
                }
            }
        }

    }

    private void parse(XMLStreamReader reader, int depth) throws XMLStreamException {
        while(true) {
            if(reader.hasNext()) {
                switch(reader.next()) {
                case XMLStreamConstants.START_ELEMENT:
                    writeBeginTag(reader.getLocalName(), depth);
                    parse(reader, depth+1);
                    break;
                case XMLStreamConstants.END_ELEMENT:
                    writeEndTag(reader.getLocalName(), depth-1);
                    return;
                }
            }
        }
    }

    private void writeBeginTag(String tag, int depth) {
        for(int i = 0; i < depth; i++) {
            System.out.print(" ");
        }
        System.out.println("<" + tag + ">");
    }

    private void writeEndTag(String tag, int depth) {
        for(int i = 0; i < depth; i++) {
            System.out.print(" ");
        }
        System.out.println("</" + tag + ">");
    }

    public static void main(String[] args) {
        StaxExample app = new StaxExample();
        app.getXml();
    }

}

There is an idiom for StAX with a loop like this for every tag in the XML:

private MyTagObject parseMyTag(XMLStreamReader reader, String myTag) throws XMLStreamException {
    MyTagObject myTagObject = new MyTagObject();
    while (true) {
        switch (reader.next()) {
        case XMLStreamConstants.START_ELEMENT:
            String localName = reader.getLocalName();
            if(localName.equals("myOtherTag1")) {
                myTagObject.setMyOtherTag1(parseMyOtherTag1(reader, localName));
            } else if(localName.equals("myOtherTag2")) {
                myTagObject.setMyOtherTag2(parseMyOtherTag2(reader, localName));
            }
            // and so on
            break;
        case XMLStreamConstants.END_ELEMENT:
            if(reader.getLocalName().equals(myTag) {
                return myTagObject;
            }
            break;
    }
}
查看更多
Root(大扎)
3楼-- · 2019-01-29 08:27

Almost any useful SAX application needs to maintain a stack. When startElement is called, you push information to the stack, when endElement is called, you pop the stack. Exactly what you put on the stack depends on the application; it's often the element name. For your application, you don't actually need a full stack, you only need to know its depth. You could get by with maintaining this using depth++ in startElement and depth-- in endElement(). Then you just output depth spaces before the element name.

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-29 08:32

well what have you tried? you should use a transformer found here: How to pretty print XML from Java?

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
查看更多
登录 后发表回答