001: /*
002: * Copyright (C) 2004, 2005, 2006 Joe Walnes.
003: * Copyright (C) 2006, 2007 XStream Committers.
004: * All rights reserved.
005: *
006: * The software in this package is published under the terms of the BSD
007: * style license a copy of which has been included with this distribution in
008: * the LICENSE.txt file.
009: *
010: * Created on 29. September 2004 by James Strachan
011: */
012: package com.thoughtworks.xstream.io.xml;
013:
014: import com.thoughtworks.xstream.converters.ErrorWriter;
015: import com.thoughtworks.xstream.io.StreamException;
016:
017: import javax.xml.namespace.QName;
018: import javax.xml.stream.XMLStreamConstants;
019: import javax.xml.stream.XMLStreamException;
020: import javax.xml.stream.XMLStreamReader;
021:
022: /**
023: * A reader using the StAX API.
024: *
025: * @author James Strachan
026: * @version $Revision: 1345 $
027: */
028: public class StaxReader extends AbstractPullReader {
029:
030: private final QNameMap qnameMap;
031: private final XMLStreamReader in;
032:
033: public StaxReader(QNameMap qnameMap, XMLStreamReader in) {
034: this (qnameMap, in, new XmlFriendlyReplacer());
035: }
036:
037: /**
038: * @since 1.2
039: */
040: public StaxReader(QNameMap qnameMap, XMLStreamReader in,
041: XmlFriendlyReplacer replacer) {
042: super (replacer);
043: this .qnameMap = qnameMap;
044: this .in = in;
045: moveDown();
046: }
047:
048: protected int pullNextEvent() {
049: try {
050: switch (in.next()) {
051: case XMLStreamConstants.START_DOCUMENT:
052: case XMLStreamConstants.START_ELEMENT:
053: return START_NODE;
054: case XMLStreamConstants.END_DOCUMENT:
055: case XMLStreamConstants.END_ELEMENT:
056: return END_NODE;
057: case XMLStreamConstants.CHARACTERS:
058: return TEXT;
059: case XMLStreamConstants.COMMENT:
060: return COMMENT;
061: default:
062: return OTHER;
063: }
064: } catch (XMLStreamException e) {
065: throw new StreamException(e);
066: }
067: }
068:
069: protected String pullElementName() {
070: // let the QNameMap handle any mapping of QNames to Java class names
071: QName qname = in.getName();
072: return qnameMap.getJavaClassName(qname);
073: }
074:
075: protected String pullText() {
076: return in.getText();
077: }
078:
079: public String getAttribute(String name) {
080: return in.getAttributeValue(null, name);
081: }
082:
083: public String getAttribute(int index) {
084: return in.getAttributeValue(index);
085: }
086:
087: public int getAttributeCount() {
088: return in.getAttributeCount();
089: }
090:
091: public String getAttributeName(int index) {
092: return unescapeXmlName(in.getAttributeLocalName(index));
093: }
094:
095: public void appendErrors(ErrorWriter errorWriter) {
096: errorWriter.add("line number", String.valueOf(in.getLocation()
097: .getLineNumber()));
098: }
099:
100: public void close() {
101: try {
102: in.close();
103: } catch (XMLStreamException e) {
104: throw new StreamException(e);
105: }
106: }
107:
108: }
|