获取值形式xml字符串java spring

时间:2018-09-17 04:09:04

标签: java xml parsing xml-parsing

这是我的XML字符串:

<soapenv:Envelope
   xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <HostCustomerResponse xmlns="http://10.25.143.133">
         <ns1:output xmlns:ns1="http://10.25.136.152"
            xmlns:ns2="java:prismagateway.service.HostCustomer" xsi:type="ns2:Output">
            <ns2:bankReffNo/>
            <ns2:statusCode>00</ns2:statusCode>
            <ns2:statusMsg/>
            <ns2:txnResponseDateTime>20180917110403</ns2:txnResponseDateTime>
            <ns2:txnData>&lt;balanceResponse&gt;&lt;balance&gt;	&lt;accountNo&gt;800000123800&lt;/accountNo&gt;		&lt;accountCurrency&gt;IDR&lt;/accountCurrency&gt;	&lt;date&gt;20180917&lt;/date&gt;	&lt;ledgerBalance&gt;23842209566.02&lt;/ledgerBalance&gt;	&lt;availableBalance&gt;23257643542.65&lt;/availableBalance&gt;    	&lt;holdAmount&gt;584566023.37&lt;/holdAmount&gt;        	&lt;overdraftLimit&gt;0&lt;/overdraftLimit&gt;        	&lt;/balance&gt;&lt;/balanceResponse&gt;</ns2:txnData>
         </ns1:output>
      </HostCustomerResponse>
   </soapenv:Body>
</soapenv:Envelope>

我如何获取ns2:statusCode的值?

1 个答案:

答案 0 :(得分:0)

如果要使用Stax解析器,则必须执行以下操作:

public static void main(String[] args) throws XMLStreamException {
      XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(
              Test.class.getResourceAsStream("test.xml")
      );
      while(xmlEventReader.hasNext()) {
        XMLEvent xmlEvent = xmlEventReader.nextEvent();
        if(xmlEvent.isStartElement()){
            if(Objects.equals(xmlEvent.asStartElement().getName().getLocalPart(),"statusCode")) {
                xmlEvent = xmlEventReader.nextEvent();
                if (xmlEvent.isCharacters()) {
                    System.out.println(xmlEvent.asCharacters().getData()); // 00
                }
            }

        }
    }
}