Module java.xml
Package javax.xml.stream

Interface XMLStreamReader

所有超级接口:
XMLStreamConstants
所有已知实现类:
StreamReaderDelegate

public interface XMLStreamReader extends XMLStreamConstants
XMLStreamReader接口允许向前、只读地访问XML。它被设计为读取XML数据的最低级别和最高效的方式。

XMLStreamReader被设计为使用next()和hasNext()方法迭代XML。可以使用诸如getEventType()、getNamespaceURI()、getLocalName()和getText()等方法访问数据;

使用初始事件类型START_DOCUMENT创建XMLStreamReader实例。在任何时刻,它都有一个当前事件,接口的方法可以访问该事件,并可以通过next()方法加载下一个事件。当前事件类型可以通过getEventType()确定,下一个事件可以通过next()方法返回。

解析事件被定义为XML声明、DTD、开始标记、字符数据、空格、结束标记、注释或处理指令。在文档的根级别可能会遇到属性或命名空间事件,这是查询操作的结果。

为了符合XML 1.0标准,XML处理器必须将已声明的未解析实体、符号声明及其关联的标识符传递给应用程序。此信息通过此接口的属性API提供。以下两个属性允许访问此信息:javax.xml.stream.notations和javax.xml.stream.entities。当当前事件是DTD时,以下调用将返回符号列表:List l = (List) getProperty("javax.xml.stream.notations");以下调用将返回实体声明列表:List l = (List) getProperty("javax.xml.stream.entities");这些属性只能在DTD事件期间访问,并且如果信息不可用,则定义为返回null。

以下表格描述了哪些方法在什么状态下有效。如果在无效状态下调用方法,该方法将抛出java.lang.IllegalStateException异常。

每个状态的有效方法
事件类型 有效方法
所有状态 getProperty()、hasNext()、require()、close()、getNamespaceURI()、isStartElement()、isEndElement()、isCharacters()、isWhiteSpace()、getNamespaceContext()、getEventType()、getLocation()、hasText()、hasName()
START_ELEMENT next()、getName()、getLocalName()、hasName()、getPrefix()、getAttributeXXX()、isAttributeSpecified()、getNamespaceXXX()、getElementText()、nextTag()
ATTRIBUTE next()、nextTag()、getAttributeXXX()、isAttributeSpecified()
NAMESPACE next()、nextTag()、getNamespaceXXX()
END_ELEMENT next()、getName()、getLocalName()、hasName()、getPrefix()、getNamespaceXXX()、nextTag()
CHARACTERS next()、getTextXXX()、nextTag()
CDATA next()、getTextXXX()、nextTag()
COMMENT next()、getTextXXX()、nextTag()
SPACE next()、getTextXXX()、nextTag()
START_DOCUMENT next()、getEncoding()、getVersion()、isStandalone()、standaloneSet()、getCharacterEncodingScheme()、nextTag()
END_DOCUMENT close()
PROCESSING_INSTRUCTION next()、getPITarget()、getPIData()、nextTag()
ENTITY_REFERENCE next()、getLocalName()、getText()、nextTag()
DTD next()、getText()、nextTag()
自版本:
1.6
参见:
  • Method Details

    • getProperty

      Object getProperty(String name) throws IllegalArgumentException
      从底层实现获取特性/属性的值
      参数:
      name - 属性的名称,不能为空
      返回:
      属性的值
      抛出:
      IllegalArgumentException - 如果名称为null
    • next

      int next() throws XMLStreamException
      获取下一个解析事件 - 处理器可以将所有连续的字符数据返回为单个块,也可以将其拆分为多个块。如果属性javax.xml.stream.isCoalescing设置为true,则元素内容必须合并,并且对于连续元素内容或CDATA部分,必须返回一个CHARACTERS事件。默认情况下,实体引用必须被展开并透明地报告给应用程序。如果无法展开实体引用,则会抛出异常。如果元素内容为空(即内容为""),则不会报告任何CHARACTERS事件。

      给定以下XML:
      <foo><!--description-->content text<![CDATA[<greeting>Hello>/greeting>]]>other content>/foo>
      在foo上调用next()的行为将是:
      1- 注释(COMMENT)
      2- 然后是字符部分(CHARACTERS)
      3- 然后是CDATA部分(另一个CHARACTERS)
      4- 然后是下一个字符部分(另一个CHARACTERS)
      5- 然后是END_ELEMENT

      注意: 空元素(例如<tag/>)将报告为两个单独的事件:START_ELEMENT、END_ELEMENT - 这保留了空元素与<tag></tag>的解析等效性。

      Returns:
      the integer code corresponding to the current parse event
      Throws:
      NoSuchElementException - if this is called when hasNext() returns false
      XMLStreamException - if there is an error processing the underlying XML source
      See Also:
    • require

      void require(int type, String namespaceURI, String localName) throws XMLStreamException
      Test if the current event is of the given type and if the namespace and name match the current namespace and name of the current event. If the namespaceURI is null it is not checked for equality, if the localName is null it is not checked for equality.
      Parameters:
      type - the event type
      namespaceURI - the uri of the event, may be null
      localName - the localName of the event, may be null
      Throws:
      XMLStreamException - if the required values are not matched.
    • getElementText

      String getElementText() throws XMLStreamException
      Reads the content of a text-only element, an exception is thrown if this is not a text-only element. Regardless of value of javax.xml.stream.isCoalescing this method always returns coalesced content.
      Precondition: the current event is START_ELEMENT.
      Postcondition: the current event is the corresponding END_ELEMENT.
      The method does the following (implementations are free to optimized but must do equivalent processing):
       if(getEventType() != XMLStreamConstants.START_ELEMENT) {
           throw new XMLStreamException(
           "parser must be on START_ELEMENT to read next text", getLocation());
       }
      
       int eventType = next();
       StringBuffer content = new StringBuffer();
       while(eventType != XMLStreamConstants.END_ELEMENT) {
           if(eventType == XMLStreamConstants.CHARACTERS
              || eventType == XMLStreamConstants.CDATA
              || eventType == XMLStreamConstants.SPACE
              || eventType == XMLStreamConstants.ENTITY_REFERENCE) {
                 buf.append(getText());
           } else if(eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
                     || eventType == XMLStreamConstants.COMMENT) {
               // skipping
           } else if(eventType == XMLStreamConstants.END_DOCUMENT) {
               throw new XMLStreamException(
               "unexpected end of document when reading element text content", this);
           } else if(eventType == XMLStreamConstants.START_ELEMENT) {
               throw new XMLStreamException(
               "element text content may not contain START_ELEMENT", getLocation());
           } else {
               throw new XMLStreamException(
               "Unexpected event type "+eventType, getLocation());
           }
           eventType = next();
       }
       return buf.toString();
       
      Returns:
      the content of a text-only element
      Throws:
      XMLStreamException - if the current event is not a START_ELEMENT or if a non text element is encountered
    • nextTag

      int nextTag() throws XMLStreamException
      Skips any white space (isWhiteSpace() returns true), COMMENT, or PROCESSING_INSTRUCTION, until a START_ELEMENT or END_ELEMENT is reached. If other than white space characters, COMMENT, PROCESSING_INSTRUCTION, START_ELEMENT, END_ELEMENT are encountered, an exception is thrown. This method should be used when processing element-only content separated by white space.
      Precondition: none
      Postcondition: the current event is START_ELEMENT or END_ELEMENT and cursor may have moved over any whitespace event.
      Essentially it does the following (implementations are free to optimized but must do equivalent processing):
       
       int eventType = next();
       while((eventType == XMLStreamConstants.CHARACTERS && isWhiteSpace()) // skip whitespace
       || (eventType == XMLStreamConstants.CDATA && isWhiteSpace())
       // skip whitespace
       || eventType == XMLStreamConstants.SPACE
       || eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
       || eventType == XMLStreamConstants.COMMENT
       ) {
           eventType = next();
       }
       if (eventType != XMLStreamConstants.START_ELEMENT && eventType != XMLStreamConstants.END_ELEMENT) {
           throw new String XMLStreamException("expected start or end tag", getLocation());
       }
       return eventType; 
       
      Returns:
      the event type of the element read (START_ELEMENT or END_ELEMENT)
      Throws:
      XMLStreamException - if the current event is not white space, PROCESSING_INSTRUCTION, START_ELEMENT or END_ELEMENT
      NoSuchElementException - if this is called when hasNext() returns false
    • hasNext

      boolean hasNext() throws XMLStreamException
      Returns true if there are more parsing events and false if there are no more events. This method will return false if the current state of the XMLStreamReader is END_DOCUMENT
      Returns:
      true if there are more events, false otherwise
      Throws:
      XMLStreamException - if there is a fatal error detecting the next state
    • close

      void close() throws XMLStreamException
      Frees any resources associated with this Reader. This method does not close the underlying input source.
      Throws:
      XMLStreamException - if there are errors freeing associated resources
    • getNamespaceURI

      String getNamespaceURI(String prefix)
      Return the uri for the given prefix. The uri returned depends on the current state of the processor.

      NOTE:The 'xml' prefix is bound as defined in Namespaces in XML specification to "http://www.w3.org/XML/1998/namespace".

      NOTE: The 'xmlns' prefix must be resolved to following namespace http://www.w3.org/2000/xmlns/

      Parameters:
      prefix - The prefix to lookup, may not be null
      Returns:
      the uri bound to the given prefix or null if it is not bound
      Throws:
      IllegalArgumentException - if the prefix is null
    • isStartElement

      boolean isStartElement()
      Returns true if the cursor points to a start tag (otherwise false)
      Returns:
      true if the cursor points to a start tag, false otherwise
    • isEndElement

      boolean isEndElement()
      Returns true if the cursor points to an end tag (otherwise false)
      Returns:
      true if the cursor points to an end tag, false otherwise
    • isCharacters

      boolean isCharacters()
      Returns true if the cursor points to a character data event
      Returns:
      true if the cursor points to character data, false otherwise
    • isWhiteSpace

      boolean isWhiteSpace()
      Returns true if the cursor points to a character data event that consists of all whitespace
      Returns:
      true if the cursor points to all whitespace, false otherwise
    • getAttributeValue

      String getAttributeValue(String namespaceURI, String localName)
      Returns the normalized attribute value of the attribute with the namespace and localName If the namespaceURI is null the namespace is not checked for equality
      Parameters:
      namespaceURI - the namespace of the attribute
      localName - the local name of the attribute, cannot be null
      Returns:
      returns the value of the attribute , returns null if not found
      Throws:
      IllegalStateException - if this is not a START_ELEMENT or ATTRIBUTE
    • getAttributeCount

      int getAttributeCount()
      Returns the count of attributes on this START_ELEMENT, this method is only valid on a START_ELEMENT or ATTRIBUTE. This count excludes namespace definitions. Attribute indices are zero-based.
      Returns:
      returns the number of attributes
      Throws:
      IllegalStateException - if this is not a START_ELEMENT or ATTRIBUTE
    • getAttributeName

      QName getAttributeName(int index)
      Returns the qname of the attribute at the provided index
      Parameters:
      index - the position of the attribute
      Returns:
      the QName of the attribute
      Throws:
      IllegalStateException - if this is not a START_ELEMENT or ATTRIBUTE
    • getAttributeNamespace

      String getAttributeNamespace(int index)
      Returns the namespace of the attribute at the provided index
      Parameters:
      index - the position of the attribute
      Returns:
      the namespace URI (can be null)
      Throws:
      IllegalStateException - if this is not a START_ELEMENT or ATTRIBUTE
    • getAttributeLocalName

      String getAttributeLocalName(int index)
      Returns the localName of the attribute at the provided index
      Parameters:
      index - the position of the attribute
      Returns:
      the localName of the attribute
      Throws:
      IllegalStateException - if this is not a START_ELEMENT or ATTRIBUTE
    • getAttributePrefix

      String getAttributePrefix(int index)
      Returns the prefix of this attribute at the provided index
      Parameters:
      index - the position of the attribute
      Returns:
      the prefix of the attribute
      Throws:
      IllegalStateException - if this is not a START_ELEMENT or ATTRIBUTE
    • getAttributeType

      String getAttributeType(int index)
      Returns the XML type of the attribute at the provided index
      Parameters:
      index - the position of the attribute
      Returns:
      the XML type of the attribute
      Throws:
      IllegalStateException - if this is not a START_ELEMENT or ATTRIBUTE
    • getAttributeValue

      String getAttributeValue(int index)
      Returns the value of the attribute at the index
      参数:
      index - 属性的位置
      返回:
      属性值
      抛出:
      IllegalStateException - 如果不是START_ELEMENT或ATTRIBUTE
    • isAttributeSpecified

      boolean isAttributeSpecified(int index)
      返回一个布尔值,指示此属性是否是默认创建的
      参数:
      index - 属性的位置
      返回:
      如果是默认属性则返回true
      抛出:
      IllegalStateException - 如果不是START_ELEMENT或ATTRIBUTE
    • getNamespaceCount

      int getNamespaceCount()
      返回在此START_ELEMENT或END_ELEMENT上声明的命名空间的计数,此方法仅在START_ELEMENT、END_ELEMENT或NAMESPACE上有效。在END_ELEMENT上,计数是即将超出范围的命名空间。这相当于为结束元素事件报告的SAX回调的信息。
      返回:
      返回此特定元素上声明的命名空间声明的数量
      抛出:
      IllegalStateException - 如果不是START_ELEMENT、END_ELEMENT或NAMESPACE
    • getNamespacePrefix

      String getNamespacePrefix(int index)
      返回在索引处声明的命名空间的前缀。如果这是默认命名空间声明,则返回null
      参数:
      index - 命名空间声明的位置
      返回:
      返回命名空间前缀
      抛出:
      IllegalStateException - 如果不是START_ELEMENT、END_ELEMENT或NAMESPACE
    • getNamespaceURI

      String getNamespaceURI(int index)
      返回在索引处声明的命名空间的URI。
      参数:
      index - 命名空间声明的位置
      返回:
      返回命名空间URI
      抛出:
      IllegalStateException - 如果不是START_ELEMENT、END_ELEMENT或NAMESPACE
    • getNamespaceContext

      NamespaceContext getNamespaceContext()
      返回当前位置的只读命名空间上下文。该上下文是瞬时的,仅在调用next()更改阅读器的状态之前有效。
      返回:
      返回一个命名空间上下文
    • getEventType

      int getEventType()
      返回一个整数代码,指示光标指向的事件类型。初始事件类型为XMLStreamConstants.START_DOCUMENT
      返回:
      当前事件的类型
    • getText

      String getText()
      将解析事件的当前值作为字符串返回,这将返回CHARACTERS事件的字符串值,返回COMMENT的值,ENTITY_REFERENCE的替换值,CDATA部分的字符串值,SPACE事件的字符串值,或DTD的内部子集的字符串值。如果已解析ENTITY_REFERENCE,则任何字符数据将报告为CHARACTERS事件。
      返回:
      当前文本或null
      抛出:
      IllegalStateException - 如果此状态不是有效的文本状态。
    • getTextCharacters

      char[] getTextCharacters()
      返回一个包含来自此事件的字符的数组。此数组应被视为只读和瞬时的。即,数组将包含文本字符,直到XMLStreamReader转移到下一个事件。尝试在那时保留字符数组或修改数组内容违反了此接口的约定。
      返回:
      当前文本或空数组
      抛出:
      IllegalStateException - 如果此状态不是有效的文本状态。
    • getTextCharacters

      int getTextCharacters(int sourceStart, char[] target, int targetStart, int length) throws XMLStreamException
      获取与CHARACTERS、SPACE或CDATA事件相关联的文本。从“sourceStart”开始的文本被复制到“target”,从“targetStart”开始。最多复制“length”个字符。返回实际复制的字符数。必须大于或等于0且小于或等于与事件关联的字符数的“sourceStart”参数。通常,请求从“sourceStart”为0开始的文本。如果实际复制的字符数少于“length”,则没有更多文本。否则,需要进行后续调用,直到检索到所有文本。例如:
      
       int length = 1024;
       char[] myBuffer = new char[ length ];
      
       for ( int sourceStart = 0 ; ; sourceStart += length )
       {
          int nCopied = stream.getTextCharacters( sourceStart, myBuffer, 0, length );
      
         if (nCopied < length)
             break;
       }
        
      如果底层源中存在任何XML错误,则可能会抛出XMLStreamException。必须大于或等于0且小于“target”的长度的“targetStart”参数。长度必须大于0且“targetStart + length”必须小于或等于“target”的长度。
      参数:
      sourceStart - 要复制的源数组中第一个字符的索引
      target - 目标数组
      targetStart - 目标数组中的起始偏移量
      length - 要复制的字符数
      返回:
      实际复制的字符数
      抛出:
      XMLStreamException - 如果底层XML源格式不正确
      IndexOutOfBoundsException - 如果targetStart < 0或> target的长度
      IndexOutOfBoundsException - 如果length < 0或targetStart + length > target的长度
      UnsupportedOperationException - 如果不支持此方法
      NullPointerException - 如果target为null
    • getTextStart

      int getTextStart()
      返回文本字符数组中存储第一个字符(此文本事件)的偏移量。
      返回:
      文本在字符数组中的起始位置
      抛出:
      IllegalStateException - 如果此状态不是有效的文本状态。
    • getTextLength

      int getTextLength()
      返回此文本事件在文本字符数组中的字符序列的长度。
      返回:
      文本的长度
      抛出:
      IllegalStateException - 如果此状态不是有效的文本状态。
    • getEncoding

      String getEncoding()
      如果已知,则返回输入编码;如果未知,则返回null。
      返回:
      此实例的编码或null
    • hasText

      boolean hasText()
      返回一个布尔值,指示当前事件是否具有文本。以下事件具有文本:CHARACTERS、DTD、ENTITY_REFERENCE、COMMENT、SPACE
      返回:
      如果事件具有文本则返回true,否则返回false
    • getLocation

      Location getLocation()
      返回处理器的当前位置。如果位置未知,则处理器应返回一个Location的实现,该实现对于位置返回-1,对于publicId和systemId返回null。位置信息仅在调用next()之前有效。
      返回:
      光标的位置
    • getName

      QName getName()
      返回当前START_ELEMENT或END_ELEMENT事件的QName
      返回:
      当前START_ELEMENT或END_ELEMENT事件的QName
      抛出:
      IllegalStateException - 如果不是START_ELEMENT或END_ELEMENT
    • getLocalName

      String getLocalName()
      返回当前事件的(本地)名称。对于START_ELEMENT或END_ELEMENT,返回当前元素的(本地)名称。对于ENTITY_REFERENCE,它返回实体名称。当前事件必须是START_ELEMENT或END_ELEMENT,或ENTITY_REFERENCE
      返回:
      本地名称
      抛出:
      IllegalStateException - 如果不是START_ELEMENT、END_ELEMENT或ENTITY_REFERENCE
    • hasName

      boolean hasName()
      返回一个布尔值,指示当前事件是否具有名称(是START_ELEMENT或END_ELEMENT)。
      返回:
      如果事件具有名称则返回true,否则返回false
    • getNamespaceURI

      String getNamespaceURI()
      如果当前事件是START_ELEMENT或END_ELEMENT,则此方法返回前缀或默认命名空间的URI。如果事件没有前缀,则返回null。
      返回:
      绑定到此元素前缀、默认命名空间或null的URI
    • getPrefix

      String getPrefix()
      返回当前事件的前缀,如果事件没有前缀则返回null
      返回:
      前缀或null
    • getVersion

      String getVersion()
      获取XML声明中声明的XML版本。如果未声明,则返回null
      返回:
      XML版本或null
    • isStandalone

      boolean isStandalone()
      从XML声明中获取独立声明
      返回:
      如果是独立的则返回true,否则返回false
    • standaloneSet

      boolean standaloneSet()
      检查文档中是否设置了独立标志
      返回:
      如果文档中设置了独立标志则返回true,否则返回false
    • getCharacterEncodingScheme

      String getCharacterEncodingScheme()
      返回XML声明中声明的字符编码。如果未声明,则返回null
      返回:
      文档中声明的编码或null
    • getPITarget

      String getPITarget()
      获取处理指令的目标
      返回值:
      目标或null
    • getPIData

      String getPIData()
      获取处理指令的数据部分
      返回值:
      数据或null