2013-04-04 100 views
2

解碼SOAP Envelope時遇到問題。 這裏是我的XMLXMLStreamReader和UnMarshalling SOAP消息

<?xml version="1.0"?> 
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:tns="http://c.com/partner/"> 
    <env:Header>c 
    <tns:MessageId env:mustUnderstand="true">3</tns:MessageId> 
    </env:Header> 
    <env:Body> 
    <GetForkliftPositionResponse xmlns="http://www.c.com"> 
     <ForkliftId>PC006</ForkliftId> 
    </GetForkliftPositionResponse> 
    </env:Body> 
</env:Envelope> 

我用下面的代碼對身體進行解碼,但它總是返回命名空間TNS:郵件ID,不以ENV:身體。我也想將XMLStreamReader轉換爲字符串以進行調試問題,這可能嗎?

XMLInputFactory xif = XMLInputFactory.newFactory(); 
     xif.setProperty("javax.xml.stream.isCoalescing", true); // decode entities into one string 

     StringReader reader = new StringReader(Message); 
     String SoapBody = ""; 
     XMLStreamReader xsr = xif.createXMLStreamReader(reader); 
     xsr.nextTag(); // Advance to header tag 
     xsr.nextTag(); // advance to envelope 
     xsr.nextTag(); // advance to body 

回答

1

最初XSR所指向的文件事件之前(即XML聲明),以及nextTag()前進到下一標籤,而不是下一個同級元素

xsr.nextTag(); // Advance to opening envelope tag 
    xsr.nextTag(); // advance to opening header tag 
    xsr.nextTag(); // advance to opening MessageId 

如果您想跳過對身體更好的成語是

boolean foundBody = false; 
while(!foundBody && xsr.hasNext()) { 
    if(xsr.next() == XMLStreamConstants.START_ELEMENT && 
    "http://www.w3.org/2003/05/soap-envelope".equals(xsr.getNamespaceURI()) && 
    "Body".equals(xsr.getLocalName())) { 
    foundBody = true; 
    } 
} 

// if foundBody == true, then xsr is now pointing to the opening Body tag. 
// if foundBody == false, then we ran out of document before finding a Body 

if(foundBody) { 
    // advance to the next tag - this will either be the opening tag of the 
    // element inside the body, if there is one, or the closing Body tag if 
    // there isn't 
    if(xsr.nextTag() == XMLStreamConstants.START_ELEMENT) { 
    // now pointing at the opening tag of GetForkliftPositionResponse 
    } else { 
    // now pointing at </env:Body> - body was empty 
    } 
} 
+0

我得到的例外 [com.sun.istack。 internal.SAXParseException2; lineNumber:6; columnNumber:3;意外元素(uri:「http://www.w3.org/2003/05/soap-envelope」,local:「Body」)。 我想讀取什麼是「後」的身體,以便我可以解開它 – 2013-04-04 14:40:29

+0

@AhmedSaleh一旦你找到了開放的'身體'標記_then_你可以使用'xsr.nextTag()'一次,以便前進身體內元素的開始標記,並從那裏開始解組。 – 2013-04-04 14:42:04

1

後xsr.nextTag()讀取的QName,從那裏你可以獲取標記名稱和前綴

QName qname = xsr.getName(); 
String pref = qname.getPrefix(); 
String name = qname.getLocalPart(); 
+0

@Evegeniy Dorofeev,我要跳到什麼是人體後... – 2013-04-04 14:37:19