java - 如何防止 JAXB 在编码期间写入未使用的 namespace

标签 java xml namespaces jaxb marshalling

有人能够在使用 JAXB 编码对象期间删除未使用的命名空间吗?这是所请求功能的链接:https://github.com/javaee/jaxb-v2/issues/103 (见说明)

是否有为此配置 JAXB 的属性? 这在 MOXy 中已经修复了吗?

我目前正在遍历需要编码的对象,并将所有需要绑定(bind)的类提取到Class[] classesToBeBound中。 然后我创建一个新的 JAXBContext.newInstance(classesToBeBound)

未使用的命名空间现在不包含在 XML 中。

我知道 xml 验证即使对于未使用的命名空间也是有效的,但对我来说这是框架应该处理的事情。

以下链接https://blogs.oracle.com/enterprisetechtips/entry/customizing_jaxb提到了各种固定的(请参阅某处文本的中间部分)但是当尝试在这些链接中找到解决方案时,链接已损坏或没有人真正解决它。

欢迎任何评论。

(编辑) 纯文本:

给定

a new instance of JAXBContext and add 2 classes with each a separate namespace. 

什么时候

marshalling a class that has these 2 classes as a property but only 1 of them is not null 

然后

I expect only the namespace of the property that is not null to be visible in the XML. 

但实际是

that both namespaces are in the xml. 

所以我的问题是如何删除或告诉 JAXB 不要写入未使用的命名空间?

将其放入 java 代码中: 鉴于

public class Foo{
  private Bar bar; //namespace something2
  private User user; //namespace user
}

时间

JAXBContext c = JAXBContext.newInstance(Foo.class, Bar.class, User.class);
...
Foo foo = new Foo();
foo.setBar(null);
foo.setUser(new User("Bob"));
marshaller.umarshal(foo);

那么我希望 xml 是

<foo xmlns="something1"  xmlns:user="user">
  <user:name>Bob</user:name>
</foo>

但 ACTUAL 是(注意 something2 命名空间)

<foo xmlns="something1" xmlns:user="user" xmlns:bar="something2">
  <user:name>Bob</user:name>
</foo>

当然这是一个简化的例子,我们的类型规范有大约 30 个不同的命名空间。

最佳答案

据我所知,这在 JAXB 中确实是不可能的 - 实际上是一个众所周知的问题。正如您所注意到的,生成的命名空间列表是那些已经在您的 JAXBContext 中注册的,而不是那些在编码时有效使用的:-(

过去,我使用了与您相同的解决方法(确定各种使用的类并将 JAXBContext 缩小到这组有限的类)。

另一种典型的解决方法是两步处理:首先使用 JAXB 进行编码,然后进行 XSLT 转换以摆脱所谓的“污染”命名空间。

关于java - 如何防止 JAXB 在编码期间写入未使用的 namespace ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22941466/

相关文章:

Android XML 架构验证

c# - 使用 XPath 的 SelectNodes 忽略节点名称中的大小写

xml - 棘手的 xpath 查询

namespaces - JAXB Impl 在编码的 xml 中生成不正确的命名空间

c++ - 为什么 std::generate 可以在没有命名空间限定符的情况下访问?

java - XMLAdapter:可配置的日期格式

java - FirebaseAuth 正在更改我当前的 Auth UID

java - 当对象不在持久性上下文中时,Hibernate 合并不查询数据库

java - 如何在 XQuery 中抑制 XML 输出的缩进

c++ - 如何在匿名命名空间中使用带有免费功能的谷歌测试?