简体   繁体   English

无法使用生成的JAXB类解析XML文件

[英]Can't parse XML files with generated JAXB classes

I am trying to generate JAXB bindings from this xsd file according to this tutorial . 我试图从生成JAXB绑定这个根据XSD文件本教程 Firstly I noticed that there are some dependencies, but I managed to get them off the same address. 首先,我注意到有一些依赖关系,但是我设法使它们脱离相同的地址。 After I downloaded them I ran 下载它们后,我跑了

xjc net_file.xsd

This did generate some java code, however unlike in the tutorial the files look like "...Type.java". 这确实生成了一些Java代码,但是与教程中的文件不同,这些文件看起来像“ ... Type.java”。 I find this inconvenient, but I could live with it. 我觉得这很不方便,但我可以接受。 After that I tried to parse the given example file: 之后,我尝试解析给定的示例文件:

File file = new File("quickstart.net.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(NetType.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
NetType net = (NetType) jaxbUnmarshaller.unmarshal(file);

However, I get the following exception: 但是,出现以下异常:

Exception in thread "main" javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"net"). Expected elements are (none)

Does anyone know what I am doing wrong? 有人知道我在做什么错吗?

I think your XML file is defined by two XSDs. 我认为您的XML文件由两个XSD定义。 See here: 看这里:

xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/netconvertConfiguration.xsd" and xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/net_file.xsd xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/netconvertConfiguration.xsd"xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/net_file.xsd

You will either miss net or configuration element. 您将错过netconfiguration元素。

I don't know how JAXB can support partial XSDs. 我不知道JAXB如何支持部分XSD。 Are you sure you follow the tutorial correctly? 您确定您正确地遵循了本教程吗? You should be able to merge these two xsd files into one (?). 您应该能够将这两个xsd文件合并为一个(?)。

Well, I found the problem. 好吧,我发现了问题。 It seems that you actually need to use the generated ObjectFactory . 看来您实际上需要使用生成的ObjectFactory I modified the code like this: 我修改了这样的代码:

    File file = new File("quickstart.net.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    JAXBElement<NetType> netElement = (JAXBElement<NetType>) jaxbUnmarshaller.unmarshal(file);

Now everything works. 现在一切正常。 I guess the reason is that the ObjectFactory has an annotated builder method: 我猜想原因是ObjectFactory有一个带注释的生成器方法:

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link NetType }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "net")
public JAXBElement<NetType> createNet(NetType value) {
    return new JAXBElement<NetType>(_Net_QNAME, NetType.class, null, value);
}

Imho this is really over-engineered but whatever :) 恕我直言,这确实是过度工程,但无论如何

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM