With MOXy and XPath, is it possible to unmarshal a list of attributes?

荒凉一梦 提交于 2019-12-01 21:42:14

UPDATE

I have been able to confirm the issue you are seeing (https://bugs.eclipse.org/353763). A fix has been added into our EclipseLink 2.3.1 and 2.4.0 streams and can be obtained from the nightly download page starting August 4th, 2011:

Workaround:

You can workaround this issue by setting your DocumentBuilderFactory to be namespace aware:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("src/forum6907225/input.xml");
    testClass = (TestClass) unmarshaller.unmarshal(doc);
    marshaller.marshal(testClass, System.out);

You are doing the mapping correctly (see below). Have you included a jaxb.properties file to specify EclipseLink MOXy as your JAXB provider?:

Test Class

package forum6907225;

import java.util.ArrayList;

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "test")
public class TestClass
{
    @XmlPath("items/item/@type")
    @XmlElement
    private ArrayList<String> itemList = new ArrayList<String>();

  // getters, setters omitted
}

Demo

package forum6907225;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.eclipse.persistence.Version;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(TestClass.class);
        System.out.println(Version.getVersionString());

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum6907225/input.xml");
        TestClass testClass = (TestClass) unmarshaller.unmarshal(xml);

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

}

input.xml

<?xml version="1.0" encoding="UTF-8"?>
<test>
  <items>
    <item type="cookie">cookie</item>
    <item type="crackers">crackers</item>
  </items>
</test>

Output

2.3.1.qualifier
<?xml version="1.0" encoding="UTF-8"?>
<test>
   <items>
      <item type="cookie"/>
      <item type="crackers"/>
   </items>
</test>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!