我有以下SOAP XML文件并尝试提取1Z跟踪号。不幸的是,我只得到一个空值。
<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0" xmlns:v3="http://www.ups.com/XMLSchema/XOLTWS/Track/v2.0" xmlns:v11="http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0">
<soapenv:Header>
<v1:UPSSecurity>
<v1:UsernameToken>
<v1:Username>abc123@xyz.com</v1:Username>
<v1:Password>password1</v1:Password>
</v1:UsernameToken>
<v1:ServiceAccessToken>
<v1:AccessLicenseNumber>50FF35A3061C</v1:AccessLicenseNumber>
</v1:ServiceAccessToken>
</v1:UPSSecurity>
</soapenv:Header>
<soapenv:Body>
<v3:TrackRequest>
<v3:InquiryNumber>1ZA1059V0300434532</v3:InquiryNumber>
</v3:TrackRequest>
</soapenv:Body>
</soapenv:Envelope>
我正在尝试从上面的XML中提取跟踪号但有投射问题。
package com.ups.xolt.codesamples;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Parser {
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse("TrackRequest.xml");
// Create XPathFactory object
XPathFactory xpathFactory = XPathFactory.newInstance();
// Create XPath object
XPath xpath = xpathFactory.newXPath();
String InquiryNumber = getInquiryNumber(doc, xpath);
System.out.println("InquiryNumber: " + InquiryNumber);
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
private static String getInquiryNumber(Document doc, XPath xpath) {
String InquiryNumber = null;
// List<String> list = new ArrayList<>();
// xpath.setNamespaceContext(arg0);
try {
XPathExpression expr =
xpath.compile("//soapenv:Envelope/soapenv:Body/v3:TrackRequest/v3:InquiryNumber/text()" );
InquiryNumber = (String) expr.evaluate(doc, XPathConstants.STRING);
// NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
// for (int i = 0; i < nodes.getLength(); i++)
// list.add(nodes.item(i).getNodeValue());
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return InquiryNumber;
}
}