有关Java到XML转换的问题,反之亦然

时间:2012-05-09 07:28:33

标签: java xml java-ee xml-parsing xml-binding

我有这样的XML,我从中间件

获得  
<Example library="somewhere">

   <book>

     <AUTHORS_TEST>Author_Name</AUTHORS_TEST>
     <EXAMPLE_TEST>Author_Name</EXAMPLE_TEST>

   </book>

</Example>

我想要做的是将XML转换为Java对象(和Vice Versa):

class Example
 {

 private String authorsTest;
 private String exampleTest;

  }

那么有没有办法映射这两个,需要注意的是XML标签名称和类属性名称是不同的,所以有人建议用最小的变化来实现吗?Xstream是一个很好的选择,但如果我有很多字段,很难添加别名,所以除了XStream之外还有更好的选择吗?

3 个答案:

答案 0 :(得分:3)

有很好的图书馆可以帮到你。一个简单的例子是XStream

请参阅Two Minute Tutorial

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

现在,要将其转换为XML,您只需要对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,因为它非常易于使用。如果你想做更复杂的事情,比如从XML生成Java类,你应该看看Miquel提到的JAXB。但它更复杂,需要更多时间才能开始。

答案 1 :(得分:3)

您正在寻找的是XML绑定,您实际上将xml转换为基于xml架构的java类。对此的参考实现是jaxb,但还有许多其他选择。

答案 2 :(得分:1)

注意:我是EclipseLink JAXB (MOXy)潜在客户和JAXB 2 (JSR-222)专家组的成员。

大多数XML绑定库在XML表示中每层嵌套都需要一个对象。 EclipseLink JAXB(MOXy)具有@XmlPath扩展,它允许基于XPath的映射来消除此限制。

示例

下面演示了@XmlPath扩展如何应用于您的用例。

package forum10511601;

import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement(name="Example")
@XmlAccessorType(XmlAccessType.FIELD)
class Example {

    @XmlAttribute
    private String library;

    @XmlPath("book/AUTHORS_TEST/text()")
    private String authorsTest;

    @XmlPath("book/EXAMPLE_TEST/text()")
    private String exampleTest;

}

<强> jaxb.properties

要将MOXy指定为JAXB提供程序,您需要在与域模型相同的程序包中添加名为jaxb.properties的文件,并带有以下条目(请参阅Specifying EclipseLink MOXy as Your JAXB Provider)。

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

<强>演示

由于MOXy是一个JAXB(JSR-222)实现,因此您使用标准的JAXB运行时API(从Java SE 6开始,它包含在JRE / JDK中)。

package forum10511601;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Example.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum10511601/input.xml");
        Example example = (Example) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(example, System.out);
    }

}

<强> input.xml中/输出

<?xml version="1.0" encoding="UTF-8"?>
<Example library="somewhere">
   <book>
      <AUTHORS_TEST>Author_Name</AUTHORS_TEST>
      <EXAMPLE_TEST>Author_Name</EXAMPLE_TEST>
   </book>
</Example>