将原始文件(二进制数据)转换为 XML 文件
我正在开发一个项目,在该项目下我必须从服务器获取原始文件并将其转换为 XML 文件。
java中有没有可用的工具可以帮助我完成这项任务,例如可以使用JAXP来解析XML文档?
I'm working on a project under which i have to take a raw file from the server and convert it into XML file.
Is there any tool available in java which can help me to accomplish this task like JAXP can be used to parse the XML document ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我想您将需要您的对象供以后使用,因此创建
MyObject
这将是一些 bean,您将从原始文件中加载值,您可以将其写入 someFile.xml或者您可以使用
TransformerFactory
如果您不需要这些对象供以后使用。I guess you will need your objects for later use ,so create
MyObject
that will be some bean that you will load the values form your Raw File and you can write this to someFile.xmlOr you con go with
TransformerFactory
if you don't need the objects for latter use.是的。这假定原始文件中的文本已经是 XML。
您从
DocumentBuilderFactory
开始获取DocumentBuilder
,然后可以使用其parse()
方法将输入流转换为>Document
,它是内部 XML 表示形式。如果原始文件包含 XML 以外的内容,您需要以某种方式扫描它(此处为您自己的代码)并使用您找到的内容从空
Document
构建。然后,我通常使用
TransformerFactory
中的Transformer
将Document
转换为文件中的 XML 文本,但可能有更简单的方法。Yes. This assumes that the text in the raw file is already XML.
You start with the
DocumentBuilderFactory
to get aDocumentBuilder
, and then you can use itsparse()
method to turn an input stream into aDocument
, which is an internal XML representation.If the raw file contains something other than XML, you'll want to scan it somehow (your own code here) and use the stuff you find to build up from an empty
Document
.I then usually use a
Transformer
from aTransformerFactory
to convert theDocument
into XML text in a file, but there may be a simpler way.JAXP 还可以用于创建一个新的空文档:
然后您可以使用该文档创建元素,并根据需要附加它们:
但是,正如 Jørn 在对您的问题的评论中指出的那样,这一切取决于您想如何处理这个“原始”文件:如何将其转换为 XML。只有你知道这一点。
JAXP can also be used to create a new, empty document:
Then you can use that Document to create elements, and append them as needed:
But, as Jørn noted in a comment to your question, it all depends on what you want to do with this "raw" file: how should it be turned into XML. And only you know that.
我认为如果您尝试将其加载到 XmlDocument 中,那就没问题了
I think if you try to load it in an XmlDocument this will be fine