1

私は単純なスキーマを持っています:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"
           xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="error"  type="xs:string">
    </xs:element>
</xs:schema>

JAXB を使用して XML スキーマから Java コードを生成しました。私は1つのクラスしか持っていません:

@XmlRegistry
public class ObjectFactory {

    private final static QName _Error_QNAME = new QName("", "error");

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: error
     * 
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "", name = "error")
    public JAXBElement<String> createError(String value) {
        return new JAXBElement<String>(_Error_QNAME, String.class, null, value);
    }

}

私は通常、次のコードを使用して XML を解析します。

 JAXBContext context = JAXBContext.newInstance(RootGenerateClass.class);
 Unmarshaller unmarshaller = context.createUnmarshaller();
 RootGenerateClass response = (RootGenerateClass) unmarshaller.unmarshal(streamWrapper.getStream());

この場合、どうすればよいですか (rootGenerateClass がありません)。私はこれを試します:

JAXBContext context = JAXBContext.newInstance(String.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
String response = (String) unmarshaller.unmarshal(streamWrapper.getStream());

もちろん、それは機能しません((

4

3 に答える 3

1

あなたができるはずObjectFactoryのパッケージに含まれていると仮定しますcom.example

JAXBContext context = JAXBContext.newInstance("com.example");
Unmarshaller unmarshaller = context.createUnmarshaller();
JAXBElement<String> responseElt = (JAXBElement<String>) unmarshaller.unmarshal(streamWrapper.getStream());
String response = responseElt.getValue();

パッケージ名を指定すると、そのパッケージ内のクラスJAXBContext.newInstanceが検索されます。ObjectFactory

于 2012-10-03T13:18:58.270 に答える
0

どうもありがとう。:)私はルート要素にラッパーを使用するだけです

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"
           xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="error" type="RetroErrorType"/>
    <xs:complexType name="RetroErrorType">
        <xs:simpleContent>
            <xs:extension base="xs:string">
            </xs:extension>
        </xs:simpleContent>
    </xs:complexType>
</xs:schema>

JAXBContext context = JAXBContext.newInstance(String.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
String response = (String) unmarshaller.unmarshal(streamWrapper.getStream());

正常に動作

于 2012-10-10T15:05:33.340 に答える
0

あなたはRootGenerateClassここであなたについて言及していません。また、アンマーシュリングとは、XML コンテンツを Java クラス オブジェクトに変換することを意味し、そのクラスには XML スキーマと同じデータ メンバーが必要です。したがって、2 番目のケースでは、Stringクラス オブジェクトへのアンマーシュは機能しません。

于 2012-10-03T13:06:38.387 に答える