2016-09-02 182 views
1

我使用屬性和xml文本反序列化xml文件。問題是這些元素具有相同的屬性。所以我總是得到錯誤,我不能在XmlType中有兩個相同的TypeNames。反序列化具有相同屬性的xml元素

我的XML:

<group_id xsi:type="xsd:int">1</group_id> 
<name xsi:type="xsd:int">myNameView</name> 

而我的C#:

 [XmlType(AnonymousType = true, Namespace = "http://www.w3.org/2001/XMLSchema", TypeName = "int")] 
[XmlRoot(ElementName = "group_id")] 
public class Group_id 
{ 
    [XmlAttribute(AttributeName = "type", Namespace = "http://www.w3.org/2001/XMLSchema-instance")] 
    public string Type { get; set; } 
    [XmlText] 
    public string Text { get; set; } 
} 
[XmlType(AnonymousType = true, Namespace = "http://www.w3.org/2001/XMLSchema", TypeName = "int")] 
[XmlRoot(ElementName = "name")] 
public class Name 
{ 
    [XmlAttribute(AttributeName = "type", Namespace = "http://www.w3.org/2001/XMLSchema-instance")] 
    public string Type { get; set; } 
    [XmlText] 
    public string Text { get; set; } 
} 

的問題是在XmlType將屬性的類型名。如果我只用一個TypeName命名一個元素,它將被正確地反序列化。

回答

1

XmlSerializer根據xsi:type屬性爲您處理類型。通過試圖自己處理這些問題,你會導致一些悲傷。

如果您聲明您的元素爲object,那麼序列化程序將使用type屬性來確定如何反序列化這些值。注意:作爲你的例子僅僅是一個片段,我假設根元素叫root

[XmlRoot("root")] 
public class Root 
{ 
    [XmlElement("group_id")] 
    public object GroupId { get; set; } 

    [XmlElement("name")] 
    public object Name { get; set; } 
} 

現在,當你反序列化你的榜樣,你實際上得到一個異常(如myNameView不是整數)。您可以通過將類型更改爲xsd:string或將該值更改爲有效整數來修復。

如果XML有效,您會發現反序列化的類型直接映射到類型屬性。有關工作演示,請參見this fiddle

相關問題