有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java和XML字符串,带参数到XML

我有一个带有参数的字符串,这是我的软件的结果

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

现在我想把这个字符串(例如,带有参数count)放在一个向量或任何其他数据结构中,然后创建XML,稍后再加载。有办法吗

谢谢


共 (1) 个答案

  1. # 1 楼答案

    您可以创建自己的JavaBean,它将保存消息、参数类型和值(如果需要,可能还有参数名)。可以使用XStreamAPI将此自定义对象从/序列化为XML。它非常简单:

    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>
    

    要重建对象,只需执行以下操作:

    Person newJoe = (Person)xstream.fromXML(xml);
    

    或者,您可以基于java标准包(SAX)准备自己的(在您的情况下很简单)反序列化实用程序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>
    

    祝你好运