简体   繁体   English

使用 StAX 读取 XML 字符串

[英]Read XML String using StAX

I am using stax for the first time to parse an XML String.我第一次使用 stax 来解析 XML 字符串。 I have found some examples but can't get my code to work.我找到了一些示例,但无法让我的代码工作。 This is the latest version of my code:这是我的代码的最新版本:

public class AddressResponseParser
{
    private static final String STATUS = "status";
    private static final String ADDRESS_ID = "address_id";
    private static final String CIVIC_ADDRESS = "civic_address";

    String status = null;
    String addressId = null;
    String civicAddress = null;

    public static AddressResponse parseAddressResponse(String response)
    {

        try
        {
            byte[] byteArray = response.getBytes("UTF-8");
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray);
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
            XMLStreamReader reader = inputFactory.createXMLStreamReader(inputStream);

            while (reader.hasNext())
            {
                int event = reader.next();

                if (event == XMLStreamConstants.START_ELEMENT)
                {
                    String element = reader.getLocalName();

                    if (element.equals(STATUS))
                    {
                        status = reader.getElementText();
                        continue;
                    }

                    if (element.equals(ADDRESS_ID))
                    {
                        addressId = reader.getText();
                        continue;
                    }

                    if (element.equals(CIVIC_ADDRESS))
                    {
                        civicAddress = reader.getText();
                        continue;
                    }
                }
            }
        }
        catch (Exception e)
        {
            log.error("Couldn't parse AddressResponse", e);
        }
    }
}

I've put watches on "event" and "reader.getElementText()".我已经将手表放在“事件”和“reader.getElementText()”上。 When the code is stopped on当代码停止时

String element = reader.getLocalName();

the "reader.getElementText()" value is displayed, but as soon as it moves away from that line it can't be evaluated.显示“reader.getElementText()”值,但一旦它离开该行,就无法对其进行评估。 When the code is stopped on:当代码停止时:

status = reader.getElementText();

the "element" watch displays the correct value. “元素”手表显示正确的值。 Finally, when I step the code one more line, I catch this exception:最后,当我将代码再执行一行时,我发现了这个异常:

(com.ctc.wstx.exc.WstxParsingException) com.ctc.wstx.exc.WstxParsingException: Current state not START_ELEMENT
 at [row,col {unknown-source}]: [1,29]

I've tried using status = reader.getText();我试过使用status = reader.getText(); instead, but then I get this exception:相反,但后来我得到了这个例外:

(java.lang.IllegalStateException) java.lang.IllegalStateException: Not a textual event (END_ELEMENT)

Can somebody point out what I'm doing wrong??有人可以指出我做错了什么吗??

EDIT:编辑:

Adding JUnit code used to test:添加用于测试的 JUnit 代码:

public class AddressResponseParserTest
{
    private String status = "OK";
    private String address_id = "123456";
    private String civic_address = "727";

    @Test
    public void testAddressResponseParser() throws UnsupportedEncodingException, XMLStreamException
    {
        AddressResponse parsedResponse = AddressResponseParser.parseAddressResponse(this.responseXML());

        assertEquals(this.status, parsedResponse.getStatus());

        assertEquals(this.address_id, parsedResponse.getAddress()
                .getAddressId());
        assertEquals(this.civic_address, parsedResponse.getAddress()
                .getCivicAddress());
    }

    private String responseXML()
    {
        StringBuffer buffer = new StringBuffer();

        buffer.append("<response>");
        buffer.append("<status>OK</status>");
        buffer.append("<address>");
        buffer.append("<address_id>123456</address_id>");
        buffer.append("<civic_address>727</civic_address>");
        buffer.append("</address>");
        buffer.append("</response>");

        return buffer.toString();
    }
}

I found a solution that uses XMLEventReader instead of XMLStreamReader:我找到了一个使用 XMLEventReader 而不是 XMLStreamReader 的解决方案:

public MyObject parseXML(String xml)
    throws XMLStreamException, UnsupportedEncodingException
{
    byte[] byteArray = xml.getBytes("UTF-8");
    ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray);
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLEventReader reader = inputFactory.createXMLEventReader(inputStream);

    MyObject object = new MyObject();

    while (reader.hasNext())
    {
        XMLEvent event = (XMLEvent) reader.next();

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

            if (element.getName().getLocalPart().equals("ElementOne"))
            {
                event = (XMLEvent) reader.next();

                if (event.isCharacters())
                {
                     String elementOne = event.asCharacters().getData();
                     object.setElementOne(elementOne);
                }
                continue;
            }
            if (element.getName().getLocalPart().equals("ElementTwo"))
            {
                event = (XMLEvent) reader.next();
                if (event.isCharacters())
                {
                     String elementTwo = event.asCharacters().getData();
                     object.setElementTwo(elementTwo);
                }
                continue;
            }
        }
    }

    return object;
}

I would still be interested in seeing a solution using XMLStreamReader.我仍然有兴趣看到使用 XMLStreamReader 的解决方案。

Make sure you read javadocs for Stax: since it is fully streaming parsing mode, only information contained by the current event is available.请确保您阅读了 Stax 的 javadocs:由于它是完全流式解析模式,因此只有当前事件包含的信息可用。 There are some exceptions, however;然而,也有一些例外; getElementText() for example must start at START_ELEMENT, but will then try to combine all textual tokens from inside current element;例如,getElementText() 必须从 START_ELEMENT 开始,但随后会尝试组合当前元素内部的所有文本标记; and when returning, it will point to matching END_ELEMENT.返回时,它将指向匹配的 END_ELEMENT。

Conversely, getText() on START_ELEMENT will not returning anything useful (since START_ELEMENT refers to tag, not child text tokens/nodes 'inside' start/end element pair).相反, START_ELEMENT 上的 getText() 不会返回任何有用的东西(因为 START_ELEMENT 指的是标记,而不是“内部”开始/结束元素对的子文本标记/节点)。 If you want to use it instead, you have to explicitly move cursor in stream by calling streamReader.next();如果你想改用它,你必须通过调用 streamReader.next(); 在流中显式移动光标。 whereas getElementText() does it for you.而 getElementText() 为你做。

So what is causing the error?那么是什么导致了错误? After you have consumed all start/end-element pairs, next token will be END_ELEMENT (matching whatever was the parent tag).在您使用完所有开始/结束元素对后,下一个标记将是 END_ELEMENT(匹配父标记的任何内容)。 So you must check for the case where you get END_ELEMENT, instead of yet another START_ELEMENT.因此,您必须检查获得 END_ELEMENT 的情况,而不是另一个 START_ELEMENT。

I faced a similar issue as I was getting "IllegalStateException: Not a textual event" message When I looked through your code I figured out that if you had a condition:我遇到了类似的问题,因为我收到了“IllegalStateException: Not a textual event”消息当我查看你的代码时,我发现如果你有一个条件:

if (event == XMLStreamConstants.START_ELEMENT){
....
addressId = reader.getText(); // it throws exception here
....
}

(Please note: StaXMan did point out this in his answer!) (请注意:StaXMan 在他的回答中确实指出了这一点!)

This happens since to fetch text, XMLStreamReader instance must have encountered 'XMLStreamConstants.CHARACTERS' event!这是因为要获取文本,XMLStreamReader 实例必须遇到“XMLStreamConstants.CHARACTERS”事件!

There maybe a better way to do this...but this is a quick and dirty fix ( I have only shown lines of code that may be of interest ) Now to make this happen modify your code slightly:也许有更好的方法来做到这一点......但这是一个快速而肮脏的修复(我只显示了可能感兴趣的代码行)现在要实现这一点,请稍微修改您的代码:

// this will tell the XMLStreamReader that it is appropriate to read the text
boolean pickupText = false

while(reader.hasNext()){

if (event == XMLStreamConstants.START_ELEMENT){
   if( (reader.getLocalName().equals(STATUS) )
   || ( (reader.getLocalName().equals(STATUS) )
   || ((reader.getLocalName().equals(STATUS) ))
         // indicate the reader that it has to pick text soon!
     pickupText = true;
   }
}else if (event == XMLStreamConstants.CHARACTERS){
  String textFromXML = reader.getText();
  // process textFromXML ...

  //...

  //set pickUpText false
  pickupText = false;

 }    

}

Hope that helps!希望有帮助!

Here is an example with XMLStreamReader:这是 XMLStreamReader 的示例:

   XMLInputFactory inputFactory = XMLInputFactory.newInstance();
   Map<String, String> elements = new HashMap<>();

try {
   XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(file);
   String elementValue = "";
   
   while (xmlReader.hasNext()) {
      int xmlEventType = xmlReader.next();
      
      switch (xmlEventType) {  
          // Check for Start Elements
          case XMLStreamConstants.START_ELEMENT:
              
              //Get current Element Name
              String elementName = xmlReader.getLocalName();
              
              if(elementName.equals("td")) {
              //Get Elements Value
              elementValue = xmlReader.getElementText();
              }
              
              //Add the new Start Element to the Map
              elements.put(elementName, elementValue);                
              break;
          default:
             break;
          }    
   }
   //Close Session
   xmlReader.close();        
} catch (Exception e) {
    log.error(e.getMessage(), e);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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