UnmarshalException错误

时间:2016-01-28 12:45:12

标签: java jaxb unmarshalling

我正在尝试解组我的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;

这是我的 unmarshaller代码

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);

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

1 个答案:

答案 0 :(得分:2)

您需要在创建DocumentBuilder之前调用setNamespaceAware()。在您创建解析器并构建DOM之后设置此项将不起作用。这很可能是JAXB无法解组根元素的原因,因为它将缺少其命名空间。

试试这个:

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