2012-02-23 84 views
0

我有一个带有参数的字符串,这是我的软件的结果。Java&XML - 带有至XML的字符串的字符串

例如,System.out.println("The number is:" + count)是结果之一。参数可以是任何类型:int,doubleDate类型。

现在我想把这个字符串(例如参数count)放在一个向量或任何其他数据结构中,然后创建XML,稍后加载它。有什么办法可以做到这一点?

谢谢。

+0

我想你会找到一个合适的解决方案[这里] [1] [1]:http://stackoverflow.com/questions/3056896/easy-xml-serializer-for-java – mac 2012-02-23 08:26:24

回答

0

您可以创建自己的java bean,它将保存消息,参数类型和值(如果需要,也可能是参数名称)。

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

XStream xstream = new XStream(); 

String xml = xstream.toXML(joe); 

将导致下面的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> 

重建你的目标只是:

这个自定义对象可以通过使用 XStream API它是非常简单的被取消/序列化从/到XML
Person newJoe = (Person)xstream.fromXML(xml); 

或者,您可以根据java标准包(SAX)准备自己的(简单的)de/serialization实用程序。 Example

你的XML可以是这样的:

<strings> 
    <mystring> 
     <message> 
      "The number is:" 
     </message> 
     <paramType> 
      int 
     </paramType> 
     <paramVal> 
      42 
     </paramVal> 
    </mystring> 
    ... 
    <mystring> 
     <message> 
      "The date is:" 
     </message> 
     <paramType> 
      Date 
     </paramType> 
     <paramVal> 
      07/04/2012 
     </paramVal> 
    </mystring> 
</strings> 

祝你好运!