如何扩展XMLStreamReader?

时间:2014-06-17 14:02:36

标签: java extends xmlstreamreader

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

我想扩展XMLStreamReader,但它是一个接口。

我想做类似的事情:

public class GraphDataStreamReader extends XMLStreamReader{

  public GraphDataStreamReader(){
    super();
  }

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

其他课程:

XMLInputFactory factory = XMLInputFactory.newInstance();
GraphDataStreamReader streamReader = (GraphDataStreamReader) factory.createXMLStreamReader(new FileReader(xmlFile)); //returns XMLStreamReader
streamReader.next(); //method from XMLStreamReader
streamReader.nextStartElement(); //method from GraphDataStreamReader
这是真的吗?如果是,那怎么办?

3 个答案:

答案 0 :(得分:2)

您可以尝试委托模式,如下所示:

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 ...
}

答案 1 :(得分:2)

以下是如何扩展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();

答案 2 :(得分:0)

我现在已经解决了(经过多次尝试)。

带有自己的方法的扩展XMLStreamReader:

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

使用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));
  }
}

感谢您的所有想法。大多数学分给麦克道尔。因为他的帖子我在努力尝试。 我希望这个问题对其他人来说仍然是有用的。