如何使用XmlList获取属性和数据列表

时间:2013-07-21 19:13:15

标签: java xml jaxb

我有XML文件,其中包含如下元素:

<element attribute1="a" attribute2="b" attribute3="c">
    a b c d e f g
</element>

有没有办法获取这两个属性并将值作为列表获取?

我可以使用@XmlList来获取一个列表[a,b,c,d,e,f,g],但是我没有这些属性。我可以为元素创建一个类并使用@XmlAttribute和@XmlValue,但是这个值不会作为列表。

如果没有办法做到这一点,我将为一个元素创建一个类,其中getter方法将String值作为数组或列表返回,这很简单,但我只是想知道是否有首先正确地解组XML的正确方法。

1 个答案:

答案 0 :(得分:1)

@XmlValue可以应用于List属性。通过此映射,列表项将在XML中表示为空格分隔列表。您可以执行以下操作:

<强>元素

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Element {

    @XmlAttribute
    private String attribute1;

    @XmlAttribute
    private String attribute2;

    @XmlAttribute
    private String attribute3;

    @XmlValue
    private List<String> value;

}

<强>演示

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

public class Demo {

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

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum17775900/input.xml");
        Element element = (Element) unmarshaller.unmarshal(xml);

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

}

<强> input.xml中/输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<element attribute1="a" attribute2="b" attribute3="c">a b c d e f g</element>