2013-07-16 76 views
1

我使用下面的代碼來獲取解組並通過Xpath查詢unmarshelled對象。 我可以在取消編組後獲取對象,但在XPath查詢時,該值爲空。EclipseLink Moxy unmarshall和getValueByXPath給出null

我是否需要指定任何NameSpaceResolver?

請讓我知道,如果你正在尋找任何進一步的信息。

我的代碼:

  JAXBContext jaxbContext = (JAXBContext) JAXBContextFactory.createContext(new Class[] {Transaction.class}, null); 
     Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); 
     StreamSource streamSource= new StreamSource(new StringReader(transactionXML)); 
     transaction = unmarshaller.unmarshal(streamSource, Transaction.class).getValue(); 
     String displayValue = jaxbContext.getValueByXPath(transaction, xPath, null, String.class); 

我的XML:

  <Transaction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:xsd="http://www.w3.org/2001/XMLSchema" > 
     <SendingCustomer firstName="test"> 

     </SendingCustomer> 
     </Transaction> 
+0

那麼你的XPath表達式是什麼? 「值爲空」 - 是字符串null(未設置)還是空的? –

回答

1

由於在您的例子中,沒有命名空間,你不用擔心撬動NamespaceResolver。您沒有提供您遇到問題的XPath,因此我在下面的示例中選擇了一個。

Java模型

交易

import javax.xml.bind.annotation.*; 

@XmlRootElement(name="Transaction") 
public class Transaction { 

    @XmlElement(name="SendingCustomer") 
    private Customer sendingCustomer; 

} 

客戶

import javax.xml.bind.annotation.XmlAttribute; 

public class Customer { 

    @XmlAttribute 
    private String firstName; 

    @XmlAttribute 
    private String lastNameDecrypted; 

    @XmlAttribute(name="OnWUTrustList") 
    private boolean onWUTrustList; 

    @XmlAttribute(name="WUTrustListType") 
    private String wuTrustListType; 

} 

DEMO CODE

input.xml中

<Transaction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <SendingCustomer firstName="test" lastNameDecrypted="SMITH" 
     OnWUTrustList="false" WUTrustListType="NONE"> 

    </SendingCustomer> 
</Transaction> 

演示

import javax.xml.bind.Unmarshaller; 
import javax.xml.transform.stream.StreamSource; 
import org.eclipse.persistence.jaxb.JAXBContext; 
import org.eclipse.persistence.jaxb.JAXBContextFactory; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     JAXBContext jaxbContext = (JAXBContext) JAXBContextFactory.createContext(new Class[] {Transaction.class}, null); 
     Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); 
     StreamSource streamSource= new StreamSource("src/forum17687460/input.xml"); 
     Transaction transaction = unmarshaller.unmarshal(streamSource, Transaction.class).getValue(); 
     String displayValue = jaxbContext.getValueByXPath(transaction, "SendingCustomer/@firstName", null, String.class); 
     System.out.println(displayValue); 
    } 

} 

輸出

test 
+1

謝謝你Blaise.Thats工作。我給了/ Transaction/SendingCustomer/@ firstName而不是SendingCustomer/@ firstName。 –

相關問題