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
Save data in an XML file
提问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
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
回答by Lukas Eder
回答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);