Read XML String using StAX

前端 未结 4 1629
天命终不由人
天命终不由人 2020-12-31 13:51

I am using stax for the first time to parse an XML String. I have found some examples but can\'t get my code to work. This is the latest version of my code:



        
4条回答
  •  清酒与你
    2020-12-31 14:10

    Here is an example with XMLStreamReader:

       XMLInputFactory inputFactory = XMLInputFactory.newInstance();
       Map 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);
    }
    

提交回复
热议问题