gpt4 book ai didi

java - UnmarshalException - 命名空间问题?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:22:45 26 4
gpt4 key购买 nike

当我尝试将 XML 解码回 java 代码时,出现以下异常。好像我在某处缺少命名空间声明,但我不确定在哪里。

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"wg_provider").
Expected elements are <{http://www.warriorgateway.org/WGProvider.xsd}wg_provider>

此文件最初是使用此处的 JAXB 编码器创建的:

    JAXBContext providerContext = JAXBContext.newInstance(WgProvider.class);
Marshaller providerMarshaller = providerContext.createMarshaller();
providerMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter providerWriter = new StringWriter();
providerMarshaller.marshal(provider, providerWriter);

这是架构文件的顶部:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.warriorgateway.org/WGProvider.xsd"
xmlns:ns1="http://www.warriorgateway.org/WGProvider.xsd"
elementFormDefault="qualified">

<xsd:element name="wg_provider">
<xsd:complexType>

这是要解码的 XML 文件的顶部:

<?xml version="1.0" encoding="UTF-8"?>
<wg_provider xmlns="http://www.warriorgateway.org/WGProvider.xsd">
<ein>26-0081701</ein>
<name>MOMS CLUB</name>
<is_virtual>false</is_virtual>
<description>
</description>

这是 JAXB 生成的 Java 文件的顶部:

@XmlRootElement(name = "wg_provider" )
public class WgProvider {

我尝试将命名空间元素添加到注释中,但没有任何区别。

这里是 package-info.xml 的内容:

@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.warriorgateway.org/WGProvider.xsd", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.warriorgateway.api.model.wg;

最后是解码代码:

for (String wrappedProviderXML : wrappedProviderXMLList) {

DocumentBuilderFactory documentbuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentbuilder = documentbuilderFactory.newDocumentBuilder();
ByteArrayInputStream xmlStream = new ByteArrayInputStream(wrappedProviderXML.getBytes());
Document providerXMLDocument = documentbuilder.parse(xmlStream);

JAXBContext wgProviderContext;
try {
wgProviderContext = JAXBContext.newInstance(WgProvider.class);
Unmarshaller wgProviderUnmarshaller = wgProviderContext.createUnmarshaller();

WgProvider wgProvider = (WgProvider) wgProviderUnmarshaller.unmarshal(providerXMLDocument);
} catch (JAXBException ex) {
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}

提前致谢

吉多

附言我正在使用 Netbeans 7 生成绑定(bind)。

最佳答案

在您的示例中,您需要将 DocumentBuilderFactory 设置为命名空间感知:

DocumentBuilderFactory documentbuilderFactory = DocumentBuilderFactory.newInstance();
documentbuilderFactory.setNamespaceAware(true);

您也可以直接解码 ByteArrayInputStream:

unmarshaller.unmarshal(xmlStream);

关于java - UnmarshalException - 命名空间问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8914319/

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