我将此响应XML作为字符串
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns:SRVResponse>
<ns:Response>
<ns1:ServiceHeader>
<ns1:rsHeader>
<ns1:status>
<ns1:finStatus>E</ns1:finStatus>
</ns1:status>
</ns1:rsHeader>
</ns1:ServiceHeader>
</ns:Response>
</ns:SRVResponse>
</soapenv:Body>
</soapenv:Envelope>
我试图获取finStatus。此标记值有时带有ns1或ns2等。但我只需要获取finStatus的值。
我尝试以下方式。
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(strResponse));
if(is != null) {
Document doc = db.parse(is);
NodeList idDetails = doc.getDocumentElement().getElementsByTagNameNS("*", "finStatus");
if(idDetails != null) {
int length = idDetails.getLength();
for (int i = 0; i < length; i++) {
if (idDetails.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) idDetails.item(i);
if (el.getNodeName().contains("finStatus")) {
status = getElementTextContent(el, "finStatus");
System.out
.println("Status :"+status);
}
}
}
}
}
getElementTextContent的方法如下
public static String getElementTextContent(Element el, String elemTag) {
String result = "";
if(el.getElementsByTagName(elemTag) != null) {
if(el.getElementsByTagName(elemTag).item(0) != null) {
if(el.getElementsByTagName(elemTag).item(0).getTextContent() != null) {
result = el.getElementsByTagName(elemTag).item(0).getTextContent();
} else {
result = "";
}
}
}
return result;
}
我没有得到任何异常,但获得空值。这个缺少什么?任何想法都将不胜感激。
答案 0 :(得分:0)
你可以尝试这个,因为这在我的代码中工作。你需要给出绝对路径
这是我正在使用的xml
* xmlInput =
* "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n"
* + " <soap:Body>\r\n" +
* " <ns1:LoginProcesRequest xmlns:ns1=\"http://xmlns.oracle.com/BioRad_jws/BR_GetSFDCLogin/GetSFDCDetailsProcess\">\r\n"
* + " <ns1:Login>1000</ns1:Login>\r\n" +
* " <ns1:Company>1000</ns1:Company>\r\n" +
* " </ns1:LoginProcesRequest>\r\n" + " </soap:Body>\r\n" +
* "</soap:Envelope>";
*/
使用
转换响应 StringWriter out = new StringWriter();
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
transformer.transform(sourceContent, new StreamResult(out));
String response = out.toString();
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(
response)));
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
header.setSessionId((String) xpath
.evaluate(
"/Envelope/Body/LoginProcessResponse/loginResponse/sessionId",
doc, XPathConstants.STRING));