【发布时间】:2021-12-19 14:12:44
【问题描述】:
我有一个表示分层 DOM 的 XML,其中每个元素都是一个 <element ...>,每个元素都有零个或多个子元素。每个<element> 都有很多属性,我不想在Element 类中乱扔所有这些属性,因为它也有很多自己的方法。
Element 类的初稿如下。这完美无缺:
class Element {
@XmlAttribute private String name;
@XmlAttribute private String bounds;
// A whole bunch of other attributes
@XmlElement(name = "element") List<Element> children;
// A whole bunch of other methods
}
我尝试通过以下方式改进:
class Element {
@XmlPath(".") private Attributes attributes;
@XmlElement(name = "element") List<Element> children;
// A whole bunch of other methods
}
class Attributes {
@XmlAttribute private String name;
@XmlAttribute private String bounds;
// A whole bunch of other attributes
}
这似乎工作正常,但是,仔细检查后它实际上会弄乱数据。如果我输入以下 XML:
<element name="Hello" bounds="[0,0][1,1]">
<element name="World" bounds="[1,1][2,2]">
<element name="Testing" bounds="[2,2][3,3]">
<element name="One two three" bounds="[3,3][4,4]" />
</element>
</element>
</element>
未编组的对象具有以下结构/属性:
+ [Element]
- name = "World"
- bounds = "[1,1][2,2]"
+ children[0]
- name = "Testing"
- bounds = "[2,2][3,3]"
+ children[0]
- name = "One two three"
- bounds = "[3,3][4,4]"
+ children[0]
- name = "One two three"
- bounds = "[3,3][4,4]"
- children = null
我的假设是XPath(".") 会将Attributes 类的属性“提升”到父Element 类。但实际上它把这些属性提升了两个层次。
当我手动构建Element 层次结构,然后尝试对其进行编组时,生成的 XML 就好了。只是解组会产生不正确的对象。
我在这里错误地使用了XPath 吗?通过将所有属性直接包含在 Element 类中,我有一个可行的解决方案,但我只想将这些属性分组到一个单独的类中并将它们编组/解组到容器 Element 类中。
谢谢! 阿西姆
【问题讨论】:
-
看起来像一个 MOXy 错误。
-
@Olivier 当然在我看来就是这样。但我怀疑它应该是这样的,因为 Moxy 已经参与了这么长时间的工作,而且肯定有人会在我之前很久就偶然发现这一点。 :(