Using @XmlPath with jaxb/MOXy to map complex type

风流意气都作罢 提交于 2019-12-30 07:24:28

问题


I have a deep XML structure with a lot of pointless wrappers I'm mapping to a single Java class. Mapping the simple datatypes with @XmlPath is a walk in the park, but when it comes to types that actually require their own class I'm not quite sure how to do it, especially when those types should be put in a list as well.

I'm having problems to map all the element types in the below example to my Element class. Since the elements wrapper resides in resource which is mapped using @XmlPath I can not use the @XmlElementWrapper, which would otherwise be the way I usually would do this.

Example XML structure

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<s:root xsi:schemaLocation="http://www.example.eu/test ResourceSchema.xsd" xmlns:s="http://www.example.eu/test" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <s:resource>
        <s:information>
            <s:date>2013-07-04</s:date>
            <s:name>This example does not work</s:name>
        </s:information>
        <s:elements>
            <s:refobj>
                <s:id>1</s:id>
                <s:source>First Source</s:source>
            </s:refobj>
            <s:refobj>
                <s:id>2</s:id>
                <s:source>Second Source</s:source>
            </s:refobj>
            <s:refobj>
                <s:id>5</s:id>
                <s:source>Fifth Source</s:source>
            </s:refobj>
        </s:elements>
    </s:resource>
</s:root>

Root.java

@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlPath("resource/information/date/text()")
    private String date;

    @XmlPath("s:resource/s:information/s:name/text()")
    private String name;

    @XmlPath("resource/elements/refobj")
    private List<RefObj> refObjs;

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

RefObj.java

@XmlRootElement(name = "refobj")
@XmlAccessorType(XmlAccessType.FIELD)
public class RefObj {

    @XmlElement(name = "id")
    private int id;

    @XmlElement(name = "source")
    private String source;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

}

Marshaller/Unmarshaller

public static void main(String[] args) {
    String xml = getXML();

    Root root = null;
    try {
        JAXBContext context = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = context.createUnmarshaller();

        StringReader stringReader = new StringReader(xml);

        root = (Root) unmarshaller.unmarshal(stringReader);
    } catch (Exception ex) {
        System.err.println("Failed to unmarshal XML!");
    }

    try {
        JAXBContext context = JAXBContext.newInstance(Root.class);
        Marshaller marshaller = context.createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.example.eu/test ResourceSchema.xsd");

        StringWriter stringWriter = new StringWriter();
        marshaller.marshal(root, stringWriter);

        System.out.println(new String(stringWriter.toString().getBytes(Charset.forName("UTF-8"))));
    } catch (Exception ex) {
        System.err.println("Failed to marshal object!");
    }

}

package-info.java

@XmlSchema(
        namespace = "http://www.example.eu/test",
        attributeFormDefault = XmlNsForm.QUALIFIED,
        elementFormDefault = XmlNsForm.QUALIFIED,
        xmlns = {
    @XmlNs(
            prefix = "s",
            namespaceURI = "http://www.example.eu/test")
},
        location = "http://www.example.eu/test ResourceSchema.xsd")
package se.example.mavenproject1;

import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

I can execute the application, but no element is mapped when I unmarshal/marshal the XML content, instead I get a XML representation containing just the information.

Update

After posting the previous example I realized that it actually worked as intended, which made me even more confused. Although I've tried to replicate the (previously) working example in my production code without any success, although I've managed to actually introduce the problems I'm having into the example code. Since I needed to add a namespace for the problems to appear I'm assuming it has something to do with naming conventions and X(ml)Path.

I've also added package-info.java and the marshaller/unmarshaller I'm using when working with those objects. Since the jaxb.properties doesn't contain anything exciting I've left it out.


回答1:


When I ran your example everything worked fine. Since your real model probably has get/set methods you will need to ensure that you add @XmlAccessorType(XmlAccessType.FIELD) to your class otherwise MOXy (or any other JAXB impl) will also treat the corresponding properties as being mapped (see: http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html).

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

@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlPath("resource/information/date/text()")
    private String date;

    @XmlPath("resource/information/name/text()")
    private String name;

    @XmlPath("resource/elements/element")
    private List<Element> elements;

}

You also need to ensure that you have a jaxb.properties file in the same package as your domain model with the following entry to specify MOXy as your JAXB provider (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).

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

For More Information

  • http://blog.bdoughan.com/2010/07/xpath-based-mapping.html

UPDATE #1

When your document is namespace qualified the @XmlPath annotation needs to factor this in. The nodes in the path can be qualified according to the @XmlSchema annotation.

package-info

In your package-info class the prefix s is assigned to the namespace URI http://www.example.eu/test.

@XmlSchema(
        namespace = "http://www.example.eu/test",
        attributeFormDefault = XmlNsForm.QUALIFIED,
        elementFormDefault = XmlNsForm.QUALIFIED,
        xmlns = {
    @XmlNs(
            prefix = "s",
            namespaceURI = "http://www.example.eu/test")
},
        location = "http://www.example.eu/test ResourceSchema.xsd")
package se.example.mavenproject1;

import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

Root

This means that the nodes qualified with the http://www.example.eu/test namespace should have the prefix s in the @XmlPath annotation.

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

@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlPath("s:resource/s:information/s:date/text()")
    private String date;

    @XmlPath("s:resource/s:information/s:name/text()")
    private String name;

    @XmlPath("s:resource/s:elements/s:element")
    private List<Element> elements;

}

UPDATE #2

So it seems as if the namespace needs to be specified in the @XmlPath when mapping the path to a complex object, but can be skipped when mapping the path to a simple object such as a String or an integer.

This is a bug. You should namespace qualify the @XmlPath for simple objects the same way you do for complex objects (see UPDATE #1). The correct mapping works today, we will fix the following bug so that the incorrect mapping behaves correctly. You can use the link below to track our progress on that issue:

  • http://bugs.eclipse.org/412311



回答2:


So it seems as if the namespace needs to be specified in the @XmlPath when mapping the path to a complex object, but can be skipped when mapping the path to a simple object such as a String or an integer.

Original, incorrect, code

@XmlPath("resource/elements/refobj")
private List<RefObj> refObjs;

Updated, working code

@XmlPath("s:resource/s:elements/s:refobj")
private List<RefObj> refObjs;

When adding the namespace prefix to the @XmlPath all the objects are mapped as expected. If anyone could confirm this, and possibly explain why, I would be most happy to know the reason for this behavior.



来源:https://stackoverflow.com/questions/17466534/using-xmlpath-with-jaxb-moxy-to-map-complex-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!