当前位置: 首页 > 知识库问答 >
问题:

UnMarshalException:意外元素(URI:“MyProtocol.xsd”,本地:“MyFrame”)。所需元素为(无)

闾丘昊然
2023-03-14
javax.xml.bind.UnmarshalException: unexpected element (uri:"MyProtocol.xsd", local:"MyFrame"). Expected elements are (none)
<?xml version="1.0" encoding="utf-8"?>
<definitions xmlns:xs="http://www.w3.org/2001/XMLSchema/"
    xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="MyProtocol.xsd"
    xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:wsi="http://ws-i.org/profiles/basic/1.1/xsd"
    xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="MyProtocol.xsd">

    <types>
        <xs:schema targetNamespace="MyProtocol.xsd"
            xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="MyProtocol.xsd"
            elementFormDefault="qualified">

            <xs:import namespace="http://ws-i.org/profiles/basic/1.1/xsd"
                schemaLocation="http://ws-i.org/profiles/basic/1.1/swaref.xsd" />

            <xs:element name="MyFrame">
                <xs:complexType>
                    <xs:choice maxOccurs="unbounded">
                        ...
public class Foobar<T>
{
   private T obj;
   private Class<T> type;

   public Foobar(Class<T> type) {
       this.type = type;
   }

   public void unmarshalXML(String xml) {
       JAXBContext jaxbContext;
       Unmarshaller unmarshaller;
       StringReader reader;

       try {
           jaxbContext = JAXBContext.newInstance(type);
           unmarshaller = jaxbContext.createUnmarshaller();

           reader = new StringReader(xml);
           obj = (T) unmarshaller.unmarshal(reader);

       } catch(JAXBException e) {
           e.printStackTrace();
       }
   }
}

Axis2生成一个stub类,它包含所有的getters、setters和schema中的选项中的类。我使用该类并调用unmarshal方法,如下所示:

Foobar<MyStub.MyFrame> foobar = new Foobar<MyStub.MyFrame>(MyStub.MyFrame.class);

// Unmarshal
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
           + "<MyFrame xmlns=\"MyProtocol.xsd\">"
           + "<YC>"
           + "<SenderId>172</SenderId>"
           + "<RequestId>123saA</RequestId>"
           + "<SubNumber>5558879876</SubNumber>"
           + "</YC>"
           + "</MyFrame>";

foobar.unmarshalXML(xml);

然后我得到上面张贴的错误。为什么会出现这种情况?我的代码错了吗?

共有1个答案

南宫泓
2023-03-14

没关系,我想出来了。如果您有以下XML:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<MyFrame>
    <Data>
        <ID>172</ID>
        <Name>101</Name>
        <Date>11241987</Date>
    </Data>
</MyFrame>

您可以使用下面的代码解封它。OP中的代码只有在使用JAXB时才起作用。然而,在我的场景中,我使用的是ADB。

解封

XMLStreamReader reader = XMLInputFactory.newInstance()
            .createXMLStreamReader(new ByteArrayInputStream(someXMLString.getBytes()));

SomeClass myClass = SomeClass.Factory.parse(reader);
OMElement omElement = myClass.getOMElement
                (SomeClass.MY_QNAME, OMAbstractFactory.getSOAP12Factory());
String someXMLString = omElement.toStringWithConsume();
 类似资料: