2016-08-03 63 views
0

我想從下面的字符串響應從Salesforce獲得標籤值,如何使用Java從SOAP響應中檢索元素值?

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

上面我們有標籤<fullName>。我需要獲取標籤內的值並將其放入String數組中。我已經嘗試過使用substring方法,但它只返回一個值。任何人都可以建議我這樣做嗎?

+0

使用[XPath]中(http://docs.oracle.com/javase/8/docs/api/javax /xml/xpath/package-summary.html)或[創建DocumentBuilder](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html#newDocumentBuilder-- ),將SOAP消息解析爲文檔,並使用[getElementsByTagName](http://docs.oracle.com/javase/8/docs/api/org/w3c/dom/Document.html#getElementsByTagName-java.lang。串-)。 – VGR

+0

我試過這種方式。這個對我有用。 – Hariprasath

回答

1

我試圖像下面,

從上面的代碼,你會得到的ID列表。在此之後,你可以把那些到字符串數組,並返回到那些字符串數組像下面,

List<String> output = getFullNameFromXml(response, "fullName"); 
String[] strarray = new String[output.size()]; 
output.toArray(strarray); 
System.out.print("Response Array is "+Arrays.toString(strarray)); 
0

如果你只是想解析這個單一元素,你可以使用SAX或StAX解析器,如https://www.javacodegeeks.com/2013/05/parsing-xml-using-dom-sax-and-stax-parser-in-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); 

或者您可能想了解更多有關JAX-WS API的信息,以創建一個SOAP客戶端來使用您的Salesforce Web服務。

+0

由於其他網站會隨着時間推移而移動或消失,因此不鼓勵使用僅限連接的答案。提供您已鏈接的信息摘要和/或簡短示例更好。 – VGR