如何使用 Java 从 SOAP 响应中检索元素值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38746897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve element value from SOAP response using Java?
提问by Hariprasath
I am trying to get the tag value from the below String response getting from salesforce,
我正在尝试从来自 salesforce 的以下字符串响应中获取标签值,
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://soap.sforce.com/2006/04/metadata">
<soapenv:Body>
<listMetadataResponse>
<result>
<createdById>00528000001m5RRAAY</createdById>
<createdByName>Hariprasath Thanarajah</createdByName>
<createdDate>1970-01-01T00:00:00.000Z</createdDate>
<fileName>objects/EmailMessage.object</fileName>
<fullName>EmailMessage</fullName>
<id />
<lastModifiedById>00528000001m5RRAAY</lastModifiedById>
<lastModifiedByName>Hariprasath Thanarajah</lastModifiedByName>
<lastModifiedDate>1970-01-01T00:00:00.000Z</lastModifiedDate>
<namespacePrefix />
<type>CustomObject</type>
</result>
</listMetadataResponse>
</soapenv:Body>
</soapenv:Envelope>
Above we had the tag <fullName>
. I'll need to get the value inside the tag and put it in the String array. I have tried with substring method but It returns only one value. Can anyone suggest me to do this?
上面我们有标签<fullName>
。我需要获取标签内的值并将其放入字符串数组中。我尝试过使用 substring 方法,但它只返回一个值。有人可以建议我这样做吗?
采纳答案by Hariprasath
I have tried like below,
我试过如下,
public static Document loadXMLString(String response) throws Exception
{
DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(response));
return db.parse(is);
}
public static List<String> getFullNameFromXml(String response, String tagName) throws Exception {
Document xmlDoc = loadXMLString(response);
NodeList nodeList = xmlDoc.getElementsByTagName(tagName);
List<String> ids = new ArrayList<String>(nodeList.getLength());
for(int i=0;i<nodeList.getLength(); i++) {
Node x = nodeList.item(i);
ids.add(x.getFirstChild().getNodeValue());
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
}
return ids;
}
From above code, you will get ids list. After that, you can put those into the String Array and return those into String array like below,
从上面的代码中,您将获得 ids 列表。之后,您可以将它们放入字符串数组并将它们返回到字符串数组中,如下所示,
List<String> output = getFullNameFromXml(response, "fullName");
String[] strarray = new String[output.size()];
output.toArray(strarray);
System.out.print("Response Array is "+Arrays.toString(strarray));
回答by Vladimiro Corsi
If you just want to parse this single element you can use a SAX or StAX parser as described here https://www.javacodegeeks.com/2013/05/parsing-xml-using-dom-sax-and-stax-parser-in-java.html.
如果您只想解析这个单个元素,您可以使用 SAX 或 StAX 解析器,如下所述https://www.javacodegeeks.com/2013/05/parsing-xml-using-dom-sax-and-stax-parser-在-java.html 中。
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean fullName = false;
public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {
System.out.println("Start Element :" + qName);
if (qName.equals("fullName")) {
fullName = true;
}
}
public void characters(char ch[], int start, int length) throws SAXException {
if (fullName ) {
System.out.println("Full Name : " + new String(ch, start, length));
fullName = false;
}
}
}
saxParser.parse(mySoapResponse, handler);
Or you may want to read more on JAX-WS API for creating a SOAP client to use your Salesforce Web Service.
或者,您可能希望阅读有关 JAX-WS API 的更多信息,以创建 SOAP 客户端以使用您的 Salesforce Web 服务。
回答by Abhishek Jha
Use the below code for parsing the SOAP response and getting the element value.
Save the XML response at any location on your system.Call the method getResult(). It is a generic method . It takes the payload class type of webservice response and returns the java object.
使用以下代码解析 SOAP 响应并获取元素值。
将 XML 响应保存在系统上的任何位置。调用 getResult() 方法。它是一种通用方法。它采用 webservice 响应的有效负载类类型并返回 java 对象。
File xmlFile = new File("response file path from step 1");
Reader fileReader = new FileReader(xmlFile);
BufferedReader bufReader = new BufferedReader(fileReader);
StringBuilder sb = new StringBuilder();
String line = bufReader.readLine();
while (line != null) {
sb.append(line).append("\n");
line = bufReader.readLine();
}
String xml2String = sb.toString();
bufReader.close();
public <T> T getResult(String xml, String path, Class<T> type) {
final Node soapBody = getSoapBody(xml, path);
return getInstance(soapBody, type);
}
private Node getSoapBody(String xml, String path) {
try {
SOAPMessage message = getSoapMessage(xml, path);
Node firstElement = getFirstElement(message);
return firstElement;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private SOAPMessage getSoapMessage(String xml, String path) throws SOAPException,
IOException {
MessageFactory factory = MessageFactory.newInstance();
FileInputStream fis = new FileInputStream(path);
BufferedInputStream inputStream = new BufferedInputStream(fis);
return factory.createMessage(new MimeHeaders(), inputStream);
}
private Node getFirstElement(SOAPMessage message) throws SOAPException {
final NodeList childNodes = message.getSOAPBody().getChildNodes();
Node firstElement = null;
for (int i = 0; i < childNodes.getLength(); i++) {
if (childNodes.item(i) instanceof Element) {
firstElement = childNodes.item(i);
break;
}
}
return firstElement;
}
private <T> T getInstance(Node body, Class<T> type) {
try {
JAXBContext jc = JAXBContext.newInstance(type);
Unmarshaller u = jc.createUnmarshaller();
return (T) u.unmarshal(body);
}
catch (JAXBException e) {
throw new RuntimeException(e);
}
}