java list xml,将XML文件转换为具有List的XML对象

I have a XML like this . And i want to convert it into JAVA object.

Hello

World

So I created following java classes with their properties.

P1 class

@XmlRootElement

public class P1 {

@XmlElement(name = "CTS")

List cts;

}

CTS class

public class CTS {

String ct;

}

Test Class

File file = new File("D:\\ContentTemp.xml");

JAXBContext jaxbContext = JAXBContext.newInstance(P1.class);

Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

P1 p = (P1) jaxbUnmarshaller.unmarshal(file);

But I am getting following error -

com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException:

2 counts of IllegalAnnotationExceptions

Class has two properties of the same name "cts"

解决方案

UPDATE

com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 2

counts of IllegalAnnotationExceptions Class has two properties of the

same name "cts"

By default a JAXB (JSR-222) implementation creates mappings based on properties and annotated fields. When you annotate a field for which there is also a property it will cause this error.

Option #1 - Use @XmlAccessorType(XmlAccessType.FIELD)

You could annotate the field you need to specify @XmlAccessorType(XmlAccessType.FIELD) on the class.

@XmlRootElement(name="P1)

@XmlAccessorType(XmlAccessType.FIELD)

public class P1 {

@XmlElement(name = "CTS")

List cts;

}

Option #2 - Annotate the Property (get method)

Alternatively you could annotate the get method.

@XmlRootElement(name="P1)

public class P1 {

List cts;

@XmlElement(name = "CTS")

public List getCts() {

return cts;

}

}

For More Information

FULL EXAMPLE

CTS

You can use the @XmlValue annotation to map to Java class to a complex type with simple content.

@XmlAccessorType(XmlAccessType.FIELD)

public class CTS {

@XmlValue

String ct;

}

P1

import java.util.List;

import javax.xml.bind.annotation.*;

@XmlRootElement(name="P1")

@XmlAccessorType(XmlAccessType.FIELD)

public class P1 {

@XmlElement(name = "CTS")

List cts;

}

Demo

import java.io.File;

import javax.xml.bind.*;

public class Demo {

public static void main(String[] args) throws Exception {

JAXBContext jc = JAXBContext.newInstance(P1.class);

Unmarshaller unmarshaller = jc.createUnmarshaller();

File xml = new File("src/forum13987708/input.xml");

P1 p1 = (P1) unmarshaller.unmarshal(xml);

Marshaller marshaller = jc.createMarshaller();

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

marshaller.marshal(p1, System.out);

}

}

input.xml/Output

Hello

World

For More Information

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值