【问题标题】:Marshalling linking exception when reading XML from namespace从命名空间读取 XML 时编组链接异常
【发布时间】:2020-04-08 21:32:17
【问题描述】:

我正在尝试编组对象并将其发送到 JMS。
我做错了什么?

QName qName = new QName("http://schema.gspt.net/EventCanonical/1.0","OrderType");
JAXBElement<OrderType> jaxbElement = new JAXBElement( qName, OrderType.class,orderType);
jaxb2Marshaller.createMarshaller().marshal(jaxbElement,sw);

javax.xml.bind.MarshalException
- with linked exception:
[com.sun.istack.internal.SAXException2: com.radial.notification.event.OrderType is not known to this 
context

这是 XML 中的命名空间

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="http://schema.gspt.net/EventCanonical/1.0" 
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://schema.gspt.net/EventCanonical/1.0" elementFormDefault="qualified" 
attributeFormDefault="unqualified">

真正有效的经典方法

JAXBContext jaxbContext = JAXBContext.newInstance(OrderType.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(orderType, sw);

【问题讨论】:

  • 什么是jaxb2Marshaller?那是JAXBContext 吗?如果是这样,它的名字很糟糕。如果是这样,它是否使用OrderType 作为注册类之一创建,即使用OrderType“上下文已知”?
  • 您的评论帮助我解决了这个问题。该课程来自 org.springframework.oxm.jaxb.Jaxb2Marshaller 。我进去看到我们可以选择将类设置为绑定。
  • marshaller.setClassesToBeBound(OrderType.class) 。这样就解决了问题

标签: java xml jaxb marshalling


【解决方案1】:

设置要绑定的类解决了问题

Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(OrderType.class)

【讨论】: