简体   繁体   中英

How to extend XMLStreamReader?

http://docs.oracle.com/javaee/5/api/javax/xml/stream/XMLStreamReader.html

I want to extend the XMLStreamReader but it's an interface.

I want to do something like:

public class GraphDataStreamReader extends XMLStreamReader{

  public GraphDataStreamReader(){
    super();
  }

  public void nextStartElement() throws XMLStreamException {
    do {
      super.next();   
    } while (!super.isStartElement());
  }
}

Other class:

XMLInputFactory factory = XMLInputFactory.newInstance();
GraphDataStreamReader streamReader = (GraphDataStreamReader) factory.createXMLStreamReader(new FileReader(xmlFile)); //returns XMLStreamReader
streamReader.next(); //method from XMLStreamReader
streamReader.nextStartElement(); //method from GraphDataStreamReader

Is this posible? If yes, then how?

You could try the delegation pattern, like this:

public class GraphDataStreamReader implements XMLStreamReader {

    private XMLStreamReader delegate;

    public GraphDataStreamReader (XMLStreamReader delegate) {
        this.delegate = delegate;
    }

    @Override
    public void close() throws XMLStreamException {
        delegate.close();
    }

    ... similar for other methods of XMLStreamReader ...

    ... then add your own methods ...
}

Here is how to extend StreamReaderDelegate :

class GraphDataStreamReader extends StreamReaderDelegate {
  public GraphDataStreamReader(XMLStreamReader reader) {
    super(reader);
  }

  public void nextStartElement() throws XMLStreamException {
    do {
      super.next();
    } while (!super.isStartElement());
  }
}

XMLInputFactory factory = XMLInputFactory.newInstance();
GraphDataStreamReader streamReader = new GraphDataStreamReader(
                                 factory.createXMLStreamReader(fileInputStream));
streamReader.next();
streamReader.nextStartElement();

I have now solved it (after alot of attempts).

The extended XMLStreamReader with own methodes:

public class GraphDataStreamReader extends XMLStreamReaderImpl {
  public GraphDataStreamReader(InputStream arg0, PropertyManager arg1) throws XMLStreamException {
    super(arg0, arg1);
  }
  public boolean nextStartElement() throws XMLStreamException {
    ....
  }
}

Class using GraphDataStreamReader:

public class GraphDataParser {
  private GraphDataStreamReader graphSR;

  private GraphDataParser(String xmlFile) throws FileNotFoundException, XMLStreamException {
    FileInputStream inStream = new FileInputStream(new File(xmlFile));
    graphSR = new GraphDataStreamReader(inStream, new PropertyManager(1));
  }
}

Thanks for all your ideas. Most credits to McDowell. Because of his post i keept trying. I hope this question is still usfull for someone else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM