gpt4 book ai didi

java - UnmarshalException 错误

转载 作者:行者123 更新时间:2023-11-30 03:04:49 25 4
gpt4 key购买 nike

我正在尝试解码我的 DOM 解析文档,以便我可以更新我的 XML。但我收到以下命名空间错误:

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Showing_Today"). Expected elements are <{http://xml.netbeans.org/schema/Shows}Showing_Today>

这是我的:package-info.java

@javax.xml.bind.annotation.XmlSchema
(namespace = "http://xml.netbeans.org/schema/Shows", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package Media;

这是我正在尝试解码的XML 文件:

  <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<Showing_Today xmlns="http://xml.netbeans.org/schema/Shows">
<movie_collection>
<Title>Red</Title>
<Director>Robert Schwentke</Director>
<Year>2010</Year>
</movie_collection>

ShowingToday.java

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"movieCollection"
})
@XmlRootElement(name = "Showing_Today")
public class ShowingToday {

@XmlElement(name = "movie_collection")
protected List<MovieType> movieCollection;

这是我的解码器代码:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document domDoc = docBuilder.parse("Now_Showing.xml");
dbf.setNamespaceAware(true);

JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(ShowingToday.class);
Binder <Node> binder = jaxbCtx.createBinder();
Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
ShowingToday shows2 = (ShowingToday) binder.unmarshal(domDoc);

我看过很多类似的问题,但没有一个解决方案有帮助。关于如何修复它有什么建议吗?谢谢

最佳答案

在创建 DocumentBuilder 之前,您需要调用 setNamespaceAware()。在创建解析器并构建 DOM 之后设置此项将不会产生任何效果。这很可能就是 JAXB 无法解码根元素的原因,因为它会丢失其 namespace 。

试试这个:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document domDoc = docBuilder.parse("Now_Showing.xml");

关于java - UnmarshalException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35061887/

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