仅 JAXB XML 编组对象,但解组需要完整结构?

发布于 2024-12-27 11:17:55 字数 706 浏览 4 评论 0原文

我正在使用标准 JAXB API 来处理 XML。我需要编组然后取消编组一个对象(因此结果应该是同一个对象)。我首先编组为字符串,然后执行相反的操作 - 从字符串解组为对象。

问题是 Marshaller.marshal(obj,os) 只给我(包含在 XML 中)。当我尝试解组回来时,我收到了有关缺少父标签的错误,这是预期的。

例如 (1) 对象“FieldSet”的编组字符串:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<FIELD1>field1</FIELD1>
<FIELD2>field2</FIELD2>

(2) 尝试将此 XML 字符串解编为“FieldSet”对象:

javax.xml.bind.UnmarshalException:不允许标记名称“FIELD1”。可能的标签名称是: - 带有链接异常: [com.sun.msv.verifier.ValidityViolation:不允许标记名称“FIELD1”。可能的标记名称为:“Parent”]

在架构中,“Parent”是应位于“FieldSet”之前的顶级元素。

为什么这些标准 JAXB 操作不对称,我需要做什么来同步它们并避免仅子/缺少父问题?谢谢。

I am using the standard JAXB API to work with XML. I need to marshal and then un-marshal an object (so the result should be the same object). I first marshal into a string, and then do the opposite -- unmarshal from a string into an object.

The problem is that Marshaller.marshal(obj,os) is giving me the child only (enclosed in XML). When I try to unmarshal back, I get errors about missing parent tags that are expected.

E.g.
(1) Marshalled String for the object "FieldSet":

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<FIELD1>field1</FIELD1>
<FIELD2>field2</FIELD2>

(2) Attempt to unmarshal this XML string into a "FieldSet" object:

javax.xml.bind.UnmarshalException: tag name "FIELD1" is not allowed. Possible tag names are:
- with linked exception:
[com.sun.msv.verifier.ValidityViolation: tag name "FIELD1" is not allowed. Possible tag names are: "Parent"]

In the schema, "Parent" is the top-level element that should precede "FieldSet".

Why are these standard JAXB operations not symmetrical, and what do I need to do synchronize them and avoid the child-only/missing parent issue? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱她像谁 2025-01-03 11:17:55

要提供根元素信息,您可以执行以下操作之一:

1 - 使用 @XmlRootElement 注释您正在注释的类

@XmlRootElement
public class FieldSet {
}

2 - 使用 JAXBElement< 的实例包装您正在编组的对象/代码>

QName qName = new QName("root");
JAXBElement<FieldSet> jaxbElement = new JAXBElement<FieldSet>(qName, FieldSet.class, fieldSet);

To supply the root element information you can do one of the following:

1 - Annotate the class that you are annotating with @XmlRootElement

@XmlRootElement
public class FieldSet {
}

2 - Wrap the object you are marshalling with an instance of JAXBElement

QName qName = new QName("root");
JAXBElement<FieldSet> jaxbElement = new JAXBElement<FieldSet>(qName, FieldSet.class, fieldSet);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文