java 将数据保存在 XML 文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5581341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:46:03  来源:igfitidea点击:

Save data in an XML file

javaxml

提问by Flash

I have an application where in i need to save the data input by a user in a form in an XML file at a specified location and i need to perform this using Java . I am relatively very new to XML handling in java. I would like some suggestions as to how to start the task .

我有一个应用程序,其中我需要将用户输入的数据以表单形式保存在 XML 文件中的指定位置,并且我需要使用 Java 执行此操作。我对 Java 中的 XML 处理比较陌生。我想要一些关于如何开始任务的建议。

Any code snippets and links will be helpful ...

任何代码片段和链接都会有所帮助...

Thank You

谢谢

回答by Jigar Joshi

There is very good framework JAXBfor this also there is Simple

有非常好的框架JAXB也有Simple

But I have used this XStream

但我用过这个 XStream

Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));

Now, to convert it to XML, all you have to do is make a simple call to XStream:

现在,要将其转换为 XML,您只需简单调用 XStream:

String xml = xstream.toXML(joe);

The resulting XML looks like this:

生成的 XML 如下所示:

<person>
  <firstname>Joe</firstname>
  <lastname>Walnes</lastname>
  <phone>
    <code>123</code>
    <number>1234-456</number>
  </phone>
  <fax>
    <code>123</code>
    <number>9999-999</number>
  </fax>
</person>

Also See

另见

回答by I82Much

I would start by looking at the XStreamlibrary. It's very simple to convert POJOs (plain old java objects) to and from XML. I have a blog postdetailing some of the gotchas.

我将首先查看XStream库。将 POJO(普通的旧 Java 对象)与 XML 相互转换非常简单。我有一篇博客文章详细介绍了一些问题。

回答by Lukas Eder

There are many open source libraries, but I would simply use JAXB, the standard. Although I have to say the XStream library suggested by other answerers looks very promising, too!

有许多开源库,但我只会使用标准JAXB。虽然我不得不说其他回答者建议的 XStream 库看起来也很有前途!

回答by Joseph Ottinger

Consider using xstream (http://x-stream.github.io/). XStream's API is very simple:

考虑使用 xstream ( http://x-stream.github.io/)。XStream 的 API 非常简单:

YourObjectGraph yourData=buildYourData();
XStream xstream=new XStream();
String yourXML=xstream.toXml(yourData);
// do something with your shiny XML

Importing is just as easy:

导入同样简单:

YourObjectGraph yourData=(YourObjectGraph)xstream.fromXml(yourXml);