java jaxb 使用命名空间解组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25819934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jaxb unmarshalling with namespace
提问by Rosh
This is my xml, need to convert it into java. I had used jaxb
这是我的xml,需要转换成java。我用过 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>
并抛出以下异常javax.xml.bind.UnmarshalException:意外元素(uri:“ http://www.ae.com/Event/Load”,本地:“Order”)。预期元素为 <{}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
订购 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>();*/
}
Can you please help me in reading also, currently reading through file, need to read as an XML String.
您能否也帮我阅读,目前正在阅读文件,需要阅读为 XML 字符串。
回答by ivan.sim
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:
命名空间属性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.*;