简体   繁体   中英

jaxb unmarshalling with namespace

This is my xml, need to convert it into java. I had used jaxb

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

And throwing the following exception javax.xml.bind.UnmarshalException: unexpected element (uri:" http://www.ae.com/Event/Load ", local:"Order"). Expected elements are <{}lm:Order>

This is my unmarshalling code

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

Order Pojo class

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>();*/

}

Can you please help me in reading also, currently reading through file, need to read as an XML String.

The namespace attribute xmlns:lm="http://www.ae.com/Event/Load" might be the culprit here. In order to specify the namespace prefix, you can add the @XmlSchema annotation to a package-info.java file like this:

@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.*;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM