获取值形式xml string java spring [duplicate]

问题描述 投票:-2回答:1

这个问题在这里已有答案:

这是我的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的值?

java xml parsing xml-parsing
1个回答
0
投票

如果你想使用Stax-parser,你必须做这样的事情:

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
                }
            }

        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.