亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

XML 未反序列化為正確的類,并且之后未使用 xsi:type 屬性進行序列化

2 回答

?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

您的示例中有幾個問題:

  • 該模型與 xml 不匹配

  • 每個 Animal 元素都會覆蓋 xsi 命名空間

  • 序列化不支持布爾值

請在下面找到有關問題的更多詳細信息:

1.模型與xml不匹配

當您指定XmlArrayItem?XmlSerializer時,將使用類型名稱作為元素名稱,或者您可以通過顯式提供ElementName來更改它。如果您使用注釋數組屬性,XmlArrayItem您將得到以下輸出:

Console.WriteLine(SerializeXml(new OuterClass { Animals = new Animal[] { new Cat(), new Dog() } }));


<OuterClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://myschema.com/">

? <Animals>

? ? <Cat>

? ? ? <Height>0</Height>

? ? ? <Weight>0</Weight>

? ? ? <Paws>0</Paws>

? ? ? <Meow>false</Meow>

? ? </Cat>

? ? <Dog>

? ? ? <Height>0</Height>

? ? ? <Weight>0</Weight>

? ? ? <Paws>0</Paws>

? ? ? <Woof>false</Woof>

? ? </Dog>

? </Animals>

</OuterClass>

如果不注釋,您將獲得 xsi:type 屬性定義的類型的輸出:


<OuterClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://myschema.com/">

? <Animals>

? ? <Animal xsi:type="Cat">

? ? ? <Height>0</Height>

? ? ? <Weight>0</Weight>

? ? ? <Paws>0</Paws>

? ? ? <Meow>false</Meow>

? ? </Animal>

? ? <Animal xsi:type="Dog">

? ? ? <Height>0</Height>

? ? ? <Weight>0</Weight>

? ? ? <Paws>0</Paws>

? ? ? <Woof>false</Woof>

? ? </Animal>

? </Animals>

</OuterClass>

XmlInclude在這種情況下,您必須向基類添加屬性。

2. 每個 Animal 元素都會覆蓋 xsi 命名空間

http://www.w3.org/2001/XMLSchema-instance是W3C中定義的特殊命名空間,可幫助序列化程序了解 XML 元素中的類型。在您的輸入 xml 中,每個 Animal 元素都會使用自定義的http://myschema.com/覆蓋此名稱空間,因此當序列化程序遇到它時xsi:type="Cat",它不知道它的含義。維基百科是了解 XML 命名空間的一個很好的起點:https://en.wikipedia.org/wiki/XML_namespace

3. XML 中的布爾值

W3C 將布爾數據類型定義為“true”、“false”、“0”和“1”,因此如果您使用值“?True?”反序列化布爾值,則會出現異常。您可能會在網上找到解決方法,但我認為您的輸入 XML 格式錯誤,您需要將 XML 中的布爾值小寫。


查看完整回答
反對 回復 2023-07-22
?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

您需要正確創建類:


            OuterClass outerClass = new OuterClass()

            {

                Animals = new Animal[] {

                    new Dog() { Name = "Watson", Height = 10, Weight = 10, Paws = 4},

                    new Cat() { Name = "Hermy", Height = 10, Weight = 10, Paws = 4}

                }

            };


查看完整回答
反對 回復 2023-07-22
  • 2 回答
  • 0 關注
  • 199 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號