EclipseLink Moxy unmarshall和getValueByXPath给出null

时间:2013-07-16 21:37:38

标签: xpath jaxb eclipselink moxy

我使用下面的代码来获取unmarshall并通过Xpath查询unmarshelled对象。 我可以在解组后获取对象,但在通过XPath查询时,该值将变为空。

我是否需要指定任何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>

1 个答案:

答案 0 :(得分:2)

由于您的示例中没有名称空间,因此您无需担心利用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