2014-09-13 86 views
2

這是我的xml,需要將它轉換爲java。我用了JAXBjaxb unmarshalling with namespace

<?xml version="1.0"?> 
<lm:order Id="PLG24M240U" JD="" aCount="2" SUCount="1" xmlns:lm="http://www.ae.com/Event/Load"> 
    <lm:master> 
    <lm:ID>3</lm:ID> 
    <lm:Number>313</lm:Number> 
    <lm:ANumber>323</lm:ANumber>  
    </lm:master> 
    <lm:detail> 
    <lm:ID>3</lm:ID> 
    <lm:Number>3131</lm:Number> 
    <lm:ANumber>3232</lm:ANumber>  
    </lm:detail> 
<lm:detail> 
    <lm:ID>3</lm:ID> 
    <lm:Number>3131</lm:Number> 
    <lm:ANumber>3232</lm:ANumber>  
    </lm:detail> 
    <lm:detail> 
    <lm:ID>3</lm:ID> 
    <lm:Number>313</lm:Number> 
    <lm:ANumber>323</lm:ANumber>  
    </lm:detail> 
</lm:order> 

和投擲以下異常 javax.xml.bind.UnmarshalException:意外的元素(URI: 「http://www.ae.com/Event/Load」,地方: 「訂單」)。預計元素< {} LM:訂單>

這是我的解組代碼

jaxbContext = JAXBContext.newInstance(Order.class); 
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); 
Order order = (Order) jaxbUnmarshaller.unmarshal(file); 
System.out.println(order); 

訂購POJO類

import java.util.ArrayList; 
import java.util.List; 

import javax.xml.bind.annotation.XmlAccessType; 
import javax.xml.bind.annotation.XmlAccessorType; 
import javax.xml.bind.annotation.XmlAttribute; 
import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlRootElement(name = "lm:Order") 
public class OrderPay { 
    @XmlAttribute 
    private String Id; 
    @XmlAttribute 
    private String JD; 
    @XmlAttribute 
    private String aCount; 
    @XmlAttribute 
    private String pCount; 
    /*@XmlElement 
    private Master master; 
    @XmlElement 
    private List<Detail> details = new ArrayList<Detail>();*/ 

} 

能否請你幫我在讀也,目前通過文件讀取,需要閱讀爲XML字符串。

+0

@isim:雅它是一個錯字,在代碼中沒有編譯時錯誤。謝謝 – Rosh 2014-09-13 06:10:32

回答

5

命名空間屬性xmlns:lm="http://www.ae.com/Event/Load"可能是這裏的罪魁禍首。爲了指定命名空間前綴,你可以在@XmlSchema註釋添加到package-info.java文件是這樣的:

@XmlSchema(
    namespace="http://www.ae.com/Event/Load", 
    elementFormDefault=XmlNsForm.QUALIFIED), 
    xmlns={@XmlNs(prefix="lm", namespaceURI="http://www.ae.com/Event/Load")}) 

package your.package; 
import javax.xml.bind.annotation.*; 
+0

亞那現在不存在錯誤。但是迴應是無效的。 System.out.println(order.getACount);是null – Rosh 2014-09-13 06:17:34

+0

StringReader reader = new StringReader(「// whole xml」); jaxbContext = JAXBContext.newInstance(Order.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Order order =(Order)jaxbUnmarshaller.unmarshal(reader); System.out.println(order); – Rosh 2014-09-13 06:22:14

+0

@Rosh我在你的XML中看不到'aCount'屬性;只有一個'Count'屬性。他們應該是一樣的嗎? – 2014-09-13 06:24:39

相關問題