gpt4 book ai didi

java - 解码意外元素错误

转载 作者:行者123 更新时间:2023-12-04 04:42:01 26 4
gpt4 key购买 nike

我有一个与这个主题非常相似的问题unexpected element error while unmarshalling ,但我仍然无法解决异常。由于 XML 和 package-info 中的 namespace 完全相同......还是因为 xsd 文件?

Exception in thread "main" javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.example.org/Uni", local:"Uni"). Expected elements are <{http://www.example.org/Uni}uni>

XML:

<?xml version="1.0" encoding="UTF-8"?>
<tns:Uni xmlns:tns="http://www.example.org/Uni" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/Uni Uni.xsd ">
<tns:Semester>
<tns:nr>1</tns:nr>
<tns:datum>01.02.2012</tns:datum>
</tns:Semester>
<tns:Semester>
<tns:nr>2</tns:nr>
<tns:datum>01.02.2012</tns:datum>
</tns:Semester>
</tns:Uni>

XSD

<complexType name="Uni">
<choice>
<element name="Semester" type="tns:Semester" maxOccurs="unbounded"></element>
</choice>
</complexType>

<complexType name="Semester">
<sequence>
<element name="nr" type="int"></element>
<element name="datum" type="string"></element>
</sequence>
</complexType>

包信息

@javax.xml.bind.annotation.XmlSchema(
namespace = "http://www.example.org/Uni", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package parserTest;

Uni.java

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

@XmlElement(name = "Semester")
protected List<Semester> semester;

public List<Semester> getSemester()
{
if (this.semester == null)
{
this.semester = new ArrayList<Semester>();
}
return this.semester;
}

}

解码

public static void main(String[] args) throws JAXBException
{
ObjectFactory factoryForElementObjects = new ObjectFactory();
List<Semester> semesterL = new ArrayList<Semester>();

Uni uni = new Uni();
uni.semester = semesterL;

JAXBContext context = JAXBContext.newInstance(Uni.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Uni un = (Uni) unmarshaller.unmarshal(new File("src/main/resources/Uni.xml"));
List<Semester> semesterA = un.semester;
System.out.println(semesterA.get(0).nr);
}

最佳答案

问题是 unmarshaller 期待元素 uni,但它找到了 Uni

为 Uni 类设置 XML 元素名称应该可以解决问题:

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

@XmlElement(name = "Semester")
protected List<Semester> semester;

public List<Semester> getSemester()
{
if (this.semester == null)
{
this.semester = new ArrayList<Semester>();
}
return this.semester;
}

}

关于java - 解码意外元素错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18744374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com