如何在java中生成XML(在String表示中) [英] How to generate XML (in String representation) in java

查看:142
本文介绍了如何在java中生成XML(在String表示中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一个java类,但只需要将这个类的一些字段输出到XML中。返回的类型必须是String。我首先选择了使用StringBuffer的最简单方法。但是,当我尝试处理输出字符串表示时,它失败了。我认为这很可能是因为有些字符在输入中没有在UTF-8中编码。有人能告诉我处理这个问题的最佳方法是什么?谢谢。

I have defined a java class, but only need to output some of the fields of this class into an XML. The returned type must be a String. I first opted for the easiest way using a StringBuffer. However, when I tried to process the output String represenation, it failed. I think it is mostly likely because there are some characters that are not encoded in the UTF-8 in the input. Could someone tell me what is the best way to handle this? Thanks.

推荐答案

XStream 一试。

引用:


让我们创建一个Person实例,并在
中填充其字段:

Let's create an instance of Person and populate its fields:



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




现在,将它转换为
XML,所有你我要做的就是对XStream进行
简单调用:

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



String xml = xstream.toXML(joe)




生成的XML如下所示:

The resulting XML looks like this:

<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> 

就这么简单。看看XML是多么干净。

It's that simple. Look at how clean the XML is.

这篇关于如何在java中生成XML(在String表示中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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