Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Java从SOAP响应中检索元素值?_Java_Xml_Soap - Fatal编程技术网

如何使用Java从SOAP响应中检索元素值?

如何使用Java从SOAP响应中检索元素值?,java,xml,soap,Java,Xml,Soap,我试图从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> <listMetad

我试图从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>

00528000001M5RRAY
哈里普拉萨特·塔纳拉贾
1970-01-01T00:00:00.000Z
对象/EmailMessage.object
电子邮件
00528000001M5RRAY
哈里普拉萨特·塔纳拉贾
1970-01-01T00:00:00.000Z
自定义对象

上面我们有标签
。我需要获取标记中的值并将其放入字符串数组中。我尝试过使用substring方法,但它只返回一个值。有人能建议我这样做吗

如果只想解析这个元素,可以使用SAX或StAX解析器,如下所述


或者,您可能想阅读更多关于JAX-WS API的内容,以创建使用Salesforce Web服务的SOAP客户端。

我已经尝试过如下方法:

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;
}
publicstaticdocumentloadxmlstring(字符串响应)引发异常
{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
InputSource is=新的InputSource(新的StringReader(响应));
返回db.parse(is);
}
公共静态列表getFullNameFromXml(字符串响应,字符串标记名)引发异常{
文档xmlDoc=loadXMLString(响应);
NodeList NodeList=xmlDoc.getElementsByTagName(标记名);
List id=newarraylist(nodeList.getLength());

对于(int i=0;i使用以下代码解析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);    
}    
}    
File xmlFile=新文件(“步骤1的响应文件路径”);
Reader fileReader=新文件读取器(xmlFile);
BufferedReader bufReader=新的BufferedReader(文件读取器);
StringBuilder sb=新的StringBuilder();
String line=bufReader.readLine();
while(line!=null){
sb.append(行)。append(“\n”);
line=bufReader.readLine();
}    
字符串xml2String=sb.toString();
bufReader.close();
公共T getResult(字符串xml、字符串路径、类类型){
最终节点soapBody=getSoapBody(xml,路径);
返回getInstance(soapBody,type);
}    
私有节点getSoapBody(字符串xml,字符串路径){
试试{
SOAPMessage=getSoapMessage(xml,路径);
节点firstElement=getFirstElement(消息);
返回第一个元素;
}    
捕获(例外e){
抛出新的运行时异常(e);
}    
}     
私有SOAPMessage getSoapMessage(字符串xml,字符串路径)引发SOAPException,
IOException{
MessageFactory=MessageFactory.newInstance();
FileInputStream fis=新的FileInputStream(路径);
BufferedInputStream inputStream=新的BufferedInputStream(fis);
返回factory.createMessage(新的MimeHeaders(),inputStream);
}    
私有节点getFirstElement(SOAPMessage消息)引发SOAPException{
final NodeList childNodes=message.getSOAPBody().getChildNodes();
Node firstElement=null;
对于(int i=0;i
使用,或者,将SOAP消息解析为文档,然后使用。我已经尝试过这种方法。它对我有效。非常感谢!!!
List<String> output = getFullNameFromXml(response, "fullName");
String[] strarray = new String[output.size()];
output.toArray(strarray);
System.out.print("Response Array is "+Arrays.toString(strarray));
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);    
}    
}