如何使用JAXB保留XML注释? [英] How to preserve XML comments with JAXB?

查看:140
本文介绍了如何使用JAXB保留XML注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不丢失注释的情况下解组和封送XML文件? 有没有使用JAXB的方法,我尝试使用以下链接 但这对我不起作用.

How to unmarshal and marshal a XML file without losing the comments? Is any way is there using JAXB, I tried example using following link but it doesn't work from me.

    <customer>
        <address>
    <!--   comments line 1 -->
           <street>1 Billing Street</street>
        </address>
        <address>
    <!-- comments line 2-->
        <street>2 Shipping Road</street>
       </address>
</customer>

我想解组上述xml,在其中添加一个新地址,然后将其编组回去,而不会丢失以下注释.

I want to unmarshal the above xml, add a new address to it and marshall it back without losing the following the comments.

<!--   comments line 1 -->
   <!-- comments line 2-->

推荐答案

@Hareesh,以便使用您提供的示例在XML文件中保留注释,您需要使用DOM(文档对象模型)来读写XML文件,而不是JAXB(如示例中所示).但是,可以使用javax.xml.bind.Binder类从从XML文件读取的文档对象中解组对象,并使用活页夹updateXML方法将对象编入文档对象,然后再将其写入XML.文件.
这样做的原因是注释保留在文档对象中,而不是JAXB对象中.您还应该查看updateJAXB方法(如果决定更新文档对象). 如果您发布的代码无效,我们会更好地帮助您.

@Hareesh in order to preserve comments in your XML file using the example you provided you need to use DOM (document object model) to read and write the XML file, not JAXB (as in the example). However, you can use the javax.xml.bind.Binder class to unmarshall your objects from the document object that your read from the XML file and use the binder updateXML method to marshall back your objects into the document object before writing it to the XML file.
The reason this works is that the comments are maintained in the document object, not the JAXB object. You should also look at the updateJAXB method (if you decide to update the document object). If you post the code that does not work we could help better.

这篇关于如何使用JAXB保留XML注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆