Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...