9

これを行う方法があれば、最もエレガントなものを知りたいです。ここに質問があります: - 抽象クラス Z があると仮定しましょう - Z から継承された 2 つのクラス、A と B という名前があります。

次のように、任意のインスタンス (A または B) をマーシャリングします。

JAXBContext context = JAXBContext.newInstance(Z.class);
Marshaller m = context.createMarshaller();
m.marshal(jaxbObject, ...an outputstream...);

結果の XML で、それがどの種類のインスタンス (A または B) であったかがわかります。

さて、どのように非整列化しますか

JAXBContext jc = JAXBContext.newInstance(Z.class);
Unmarshaller u = jc.createUnmarshaller();
u.unmarshal(...an inputstream...)

UnmarshalException というメッセージが表示されます

"Exception Description: A descriptor with default root element {<my namespace>}<the root tag, e.g. A or B> was not found in the project]

javax.xml.bind.UnmarshalException"

では、Z のインスタンスを取得し、アンマーシャリング後にテストできるようにアンマーシャリングを行うにはどうすればよいでしょうか? たとえば、z instanceof A の場合... z instanceof B の場合、何か他のもの... など。

アイデアや解決策をありがとう。

MOXy を JAXB Impl として JRE1.6 を使用しています。

4

4 に答える 4

4

ここに同様の質問があります。

提供することPerson.classでアンマーシャリングすることは可能ですReceiverPerson.classSenderPerson.class?

@XmlRootElement(name="person")
public class ReceiverPerson extends Person {
  // receiver specific code
}

@XmlRootElement(name="person")
public class SenderPerson extends Person {
  // sender specific code (if any)
}

// note: no @XmlRootElement here
public class Person {
  // data model + jaxb annotations here
}
于 2011-04-01T14:51:24.897 に答える
1

では、Z のインスタンスを取得してアンマーシャリング後にテストできるように、アンマーシャリングをどのように行うのですか? たとえば、z instanceof A の場合... z instanceof B の場合 >何か他のもの...など。

これはうまくいくはずです...

Unmarshaller u = jc.createUnmarshaller();
Object ooo = u.unmarshal( xmlStream );
if ( ooo instanceof A )
{
    A myAclass = (A)ooo;
}
else if ( ooo instanceof B )
{
    B myBclass = (B)ooo;
}

私はこれを自分でテストしましたが、動作します。

于 2011-08-25T20:00:38.660 に答える
1

私の質問に対する解決策はありません!

どのような状況でも、アンマーシャリング先のオブジェクトをアンマーシャラーに正確に伝える必要があります。

于 2011-05-02T08:22:19.723 に答える
0

すべての XML ドキュメントにはルート要素が必要であり、両方のインスタンスに同じ UnMarshaller を使用する場合は、次のような共通のルート要素を使用するしかありません。

<root>
  <A></A>
</root>

xsdファイルは次のようになります

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:annotation>
        <xs:documentation>
        example for stackoverflow
    </xs:documentation>
    </xs:annotation>
    <xs:element name="root" type="rootType"/>
    <xs:complexType name="rootType">
            <xs:choice>
                <xs:element name="A" type="AType"/>
                <xs:element name="B" type="BType"/>
            </xs:choice>
    </xs:complexType>

    ... your AType and BType definitions here

</xs:schema>
于 2011-04-01T12:42:41.167 に答える