【问题标题】:XStream: How do I map xml mixed attributes and elements to POJOs?XStream:如何将 xml 混合属性和元素映射到 POJO?
【发布时间】:2010-02-23 22:06:05
【问题描述】:

这一定是一个新手问题,但我无法从http://x-stream.github.io/得到它。

嗯,我有以下 xml 字符串

<cat age="4" >
   <name>Garfield</name>
</cat>

需要映射到:

class Cat {
  int age;
  String name;
}

有没有一种使用 XStream 的简单方法来做到这一点?如果没有,我还能尝试什么?

提前致谢。

【问题讨论】:

    标签: java xstream xml-deserialization


    【解决方案1】:

    像这样注释你的类(查看http://x-stream.github.io/annotations-tutorial.html了解详情):

    @XStreamAlias("cat")
    class Cat {
      @XStreamAsAttribute
      int age;
      String name;
    }
    

    现在只需按如下方式使用 XStream:

    xstream = new XStream();
    xstream.processAnnotations(Cat.class);
    Cat roundtripGarfield = (Cat)xstream.fromXML(xstream.toXML(garfield));
    

    【讨论】:

    • 只是在写同样的东西。添加注释文档的链接:xstream.codehaus.org/annotations-tutorial.html
    • +1 我完全没想到会有一个注释。应该好好想想……
    • 谢谢克里斯托弗——我很感激这个提示(并随时检查答案,看看它是否值得;已经发布了)。
    • 感谢提示,顺便说一句,没有注释 xstream.aliasAttribute(Cat.class, "age", "age") 也对我有用。
    【解决方案2】:

    实际上,XStream 网站上有一个答案——在转换器教程中;)

    来自http://x-stream.github.io/converter-tutorial.html

        public Object unmarshal(HierarchicalStreamReader reader,
                        UnmarshallingContext context) {
                Birthday birthday = new Birthday();
                if (reader.getAttribute("gender").charAt(0) == 'm') {
                        birthday.setGenderMale();
                } else {
                        birthday.setGenderFemale();
                }
                reader.moveDown();
                Person person = (Person)context.convertAnother(birthday, Person.class);
                birthday.setPerson(person);
                reader.moveUp();
                reader.moveDown();
                Calendar date = (Calendar)context.convertAnother(birthday, Calendar.class);
                birthday.setDate(date);
                reader.moveUp();
                return birthday;
        }
    

    (它在页面上的最后一个示例/代码块中。)

    HTH

    编辑:只是想补充一点,您需要完成整个教程,而不仅仅是寻找那个代码块。您需要创建自己的转换器并将其注册到您的 XStream 实例中。 (可能很明显,但以防万一......)

    【讨论】:

      【解决方案3】:

      您可以使用 XPath。

      它在现代 JVM 上的速度非常快,而且是一种可转移的技能。例如。您可以在 .NET 等上使用 XPath

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-02
        • 2011-04-13
        • 2011-11-28
        • 2015-05-02
        • 2014-07-12
        • 2012-09-07
        • 2012-09-16
        • 1970-01-01
        相关资源
        最近更新 更多