JAXB 2.0 - 如何跳过节点处理并将它们作为字符串返回
我正在使用 JAXB 2.0 处理 XML 文档,其中我需要映射到 Java 对象的信息(在我的示例中为“id”)并运行一些业务逻辑。这里一切正常。
但是这些 XML 文档总是包含大约 500 个节点的集合,我只想以原始 xml 格式保存到数据库中,所以我只对字符串形式的 XML 感兴趣。在我看来,将这些节点解组为 Java 对象,然后再次将它们编组为 XML 以将它们保存到数据库中是没有意义的。
有什么方法可以注释属性并使其仅将整个 XML 节点保存为字符串吗?这是该类的当前版本:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Parent {
@XmlElement(name = "id")
public long id;
@XmlElement(name = "child", type = String.class)
@XmlElementWrapper(name = "children")
public List<String> children = new ArrayList<String>();
}
解组 XML 文档后,children.size() 返回正确的 childran 数量,但它们仍然为 null。
XML 文档如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent>
<id>45</id>
<children>
<child>
<name>Crash Dummy</name>
<age>21</age>
</child>
<child>
<name>Rockstar Programmer</name>
<age>12</age>
</child>
</children>
</parent>
预先感谢您的每一个提示或可能的解决方案。
I am processing XML documents with JAXB 2.0 where I need information(in my example 'id') mapped to Java objects and run some business logic with. Everything works fine here.
But these XML documents always hold a collection of approximately 500 nodes that I just want to save to a database in the original xml format, so I am just interested in the XML in form of a String. In my opinion it makes no sense to unmarshal these nodes to Java objects and later on marshal them again into XML to save them into the database.
Is there any way to annotate a property and make it just hold the whole XML node as a String? Here is my current version of that class:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Parent {
@XmlElement(name = "id")
public long id;
@XmlElement(name = "child", type = String.class)
@XmlElementWrapper(name = "children")
public List<String> children = new ArrayList<String>();
}
After unmarshalling an XML document children.size() returns the correct number of childran but they are still null.
The XML document looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent>
<id>45</id>
<children>
<child>
<name>Crash Dummy</name>
<age>21</age>
</child>
<child>
<name>Rockstar Programmer</name>
<age>12</age>
</child>
</children>
</parent>
Thanks in advance for every hint or a possible solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,JAXB 不允许这样的事情(我所知道的任何其他基于树的 XML API 也不允许)。
我不认为解析整个文档的开销会那么糟糕。毕竟,无论如何都需要解析文档,以便找出静态节点树的开始位置和结束位置。将节点树存储为 JAXB 节点并不比将其存储在大型 blob 中差多少。
如果性能对您来说真的那么重要,我会建议两种选择:
No, JAXB does not allow something like this (nor does any other tree-based XML API that I know of).
I don't believe that the overhead for parsing the whole document will be that bad though. After all, the document needs to be parsed anyway, in order to find out where your static node tree starts and where it ends. Storing the node tree as JAXB nodes is not that much worse than having it in a large blob.
If performance is really that critical for you, I would suggest two alternatives: