【问题标题】:StAX get current event after calling getElementText()StAX 在调用 getElementText() 后获取当前事件
【发布时间】:2012-03-22 15:34:52
【问题描述】:

根据stax specificationgetElementText() 返回文本数据并将当前事件作为END_ELEMENT

我如何访问这个END_ELEMENT,因为XMLEventReader 没有任何方法可以访问当前事件? peek()next() 方法在 XML 中提供下一个事件。

【问题讨论】:

  • 为什么需要结束元素,它不包含任何有用的东西?
  • 我的代码需要将 xml 流拆分为不同的文件。我能够使用提供的答案克服。

标签: java xml stax


【解决方案1】:

你最好解释事件

            while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();

            if (event.isStartElement()) {
                StartElement startElement = event.asStartElement();

                // check the element
                if (startElement.getName().getLocalPart() == ("MyTag")) {

                    // We read the attributes from this tag

                    @SuppressWarnings("unchecked")
                    Iterator<Attribute> attributes = (Iterator<Attribute>) startElement
                            .getAttributes();
                    while (attributes.hasNext()) {
                        Attribute attribute = attributes.next();
                        if (attribute.getName().toString().equals("myattribute")) {
                            System.out.println("Attribute Value: " + attribute.getValue());
                        }
                    }
                }

                if (event.isEndElement()) {
                EndElement endElement = event.asEndElement();
                    if (endElement.getName().getLocalPart() == ("MyTag")) { 
                    // do Something 
                    }
                }
            } // end while

【讨论】:

    猜你喜欢
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 2014-05-11
    • 2014-12-24
    相关资源
    最近更新 更多