私は JAXB を使用して、Java クライアントを実装している Web サービスへの要求と応答をマーシャリングおよびアンマーシャリングしています。ただし、アンマーシャリングする必要がある次の応答に固執しています。
<ResultCollection xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<FailedItems xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:KeyValueOflongstring>
<a:Key>12345</a:Key>
<a:Value>Some clever message here</a:Value>
</a:KeyValueOflongstring>
</FailedItems>
<SucceededItems xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
</ResultCollection>
応答を Java オブジェクトとして表すために、次のドメイン クラスを使用しています。
@XmlRootElement(name="ResultCollection")
public class ResultCollectionResponse
{
@XmlElementWrapper(name="FailedItems", namespace="http://schemas.microsoft.com/2003/10/Serialization/Arrays")
@XmlElement(name = "KeyValueOflongstring")
public List<KeyValueOflongstring> FailedItems = new ArrayList<KeyValueOflongstring>();
@XmlElementWrapper(name="SucceededItems", namespace="http://schemas.microsoft.com/2003/10/Serialization/Arrays")
@XmlElement(name = "long")
public List<Long> SucceededItems = new ArrayList<Long>();
}
public class KeyValueOflongstring
{
public Long Key;
public String Value;
}
次に、非整列化するために次のことを行っています。
JAXBContext jc = JAXBContext.newInstance(ResultCollectionResponse.class);
Unmarshaller u = jc.createUnmarshaller();
// inputStream holds the XML content from the web service
ResultCollectionResponse response = (ResultCollectionResponse)u.unmarshal(inputStream);
アンマーシャリングは問題なく行われます。ResultCollectionResponse
オブジェクトは 2 つのリストで作成されます。SucceededItems
は空で、FailedItems
アイテムが 1 つあります。ただし、Key
そのValue
アイテムは null です。私はこれが XML 名前空間に関係していると考えていますが、それを修正する方法を理解することはできません。
Java コードでダミー オブジェクトを作成し、それらを XML にマーシャリングするという、いわば逆の方法を試してみました。これを行うと、次の XML になります。
<ResultCollection xmlns:ns2="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<FailedItems>
<ns2:KeyValueOflongstring>
<Key>12345678</Key>
<Value>Some clever message here</Value>
</ns2:KeyValueOflongstring>
</FailedItems>
<SucceededItems/>
</ResultCollection>
ご覧のとおり、名前空間はFailedItems
andSucceededItems
要素ではなく最上位要素に適用されています。それがなぜなのかわかりません。また、ご覧のとおり、トップ レベル要素にhttp://www.w3.org/2001/XMLSchema-instanceunexpected element (uri:"", local:"ResultCollection"). Expected elements are <{http://www.w3.org/2001/XMLSchema-instance}ResultCollection>
名前空間がありません。応答 XML には名前空間が明確に含まれているため、このエラー メッセージはさらに混乱を招きます。
私は通常 Java を扱うことはなく、XML 名前空間は私が常に無視しようとしてきたものです。どんな助けでも大歓迎です。