简体   繁体   English

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

[英]Issue regarding Java to XML conversion and vice versa

I have XML like this which I get from middleware 我有这样的XML,我从中间件获得

<Example library="somewhere">

   <book>

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

   </book>

</Example>

What I want to do is convert the XML to Java object(and Vice Versa) as: 我想做的是将XML转换为Java对象(反之亦然):

class Example
 {

 private String authorsTest;
 private String exampleTest;

  }

So Is there any way to map these two,The thing to be noted is that XML Tag Name and the Class attribute name is different,So can anyone suggest to implement this with minimal changes?Xstream is a good Choice,but if I have large number of fields it will be difficult to add aliases,so any better choices other than XStream? 所以有什么办法可以映射这两者,需要注意的是XML Tag Name和Class属性名是不同的,所以有人可以建议以最小的更改实现它吗?Xstream是一个不错的选择,但是如果我有很多字段的数量将很难添加别名,因此除了XStream之外还有其他更好的选择吗?

There are good libraries which does this for you. 有很好的库可以为您完成此任务。 An easy one is XStream for example. 一个简单的例子就是XStream

See this example from the Two Minute Tutorial : 请参阅两分钟教程中的以下示例

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

Now, to convert it to XML, all you have to do is make a simple call to XStream: 现在,要将其转换为XML,您要做的就是简单地调用XStream:

String xml = xstream.toXML(joe);

The resulting XML looks like this: 生成的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>

I would prefer XStream because it is very easy to use. 我更喜欢XStream,因为它非常易于使用。 If you want to do more complex things like generating Java classes from the XML you should have a look at JAXB as Miquel mentioned. 如果您想做更复杂的事情,例如从XML生成Java类,您应该看看Miquel提到的JAXB But it is more complex and needs more time to get started. 但这更复杂,需要更多时间才能开始。

What you are looking for is called XML Binding, where you actually turn an xml into a java class based on an xml schema. 您正在寻找的被称为XML绑定,您实际上在其中将xml转换为基于xml模式的java类。 The reference implementation for this is jaxb but there are many other alternatives. 对此的参考实现是jaxb,但还有许多其他选择。

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group. 注意:我是EclipseLink JAXB(MOXy)的负责人,并且是JAXB 2(JSR-222)专家组的成员。

Most XML-binding libraries require an object per level of nesting in the XML representation. 大多数XML绑定库在XML表示形式的每层嵌套中都需要一个对象。 EclipseLink JAXB (MOXy) has the @XmlPath extension that enables XPath based mapping to remove this restriction. EclipseLink JAXB(MOXy)具有@XmlPath扩展名,该扩展名使基于XPath的映射可以消除此限制。

Example

Below is a demonstration of how the @XmlPath extension can be applied to your use case. 以下演示了如何将@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 jaxb.properties

To specify MOXy as your JAXB provider you need to add a file named jaxb.properties in the same package as your domain model with the following entry (see Specifying EclipseLink MOXy as Your JAXB Provider ). 要将MOXy指定为JAXB提供程序,需要在与域模型相同的包中添加一个名为jaxb.properties的文件,并带有以下条目(请参阅将EclipseLink MOXy指定为JAXB提供程序 )。

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

Demo 演示版

As MOXy is a JAXB (JSR-222) implementation, you use the standard JAXB runtime APIs (which are included in the JRE/JDK starting with Java SE 6). 由于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/Output 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM