2010-04-30 76 views
3

我學習XML序列化和滿足的問題,我有兩個claess未知屬性XSI:類型的XmlSerializer

[System.Xml.Serialization.XmlInclude(typeof(SubClass))] 
public class BaseClass 
{ 

} 

public class SubClass : BaseClass 
{ 
} 

我試圖序列化一個子類對象到XML文件中,我使用的打擊代碼

XmlSerializer xs = new XmlSerializer(typeof(Base)); 
xs.Serialize(fs, SubClassObject); 

我注意到序列化成功,但XML文件是一種像

<?xml version="1.0"?> 
<BaseClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="SubClass"> 
... 
</Employee> 

如果我使用

XmlSerializer xs = new XmlSerializer(typeof(Base)); 
SubClassObject = xs.Deserialize(fs) as SubClass; 

我注意到它會抱怨XSI:類型是未知的屬性(我註冊的事件),但嵌入XML的所有信息被成功解析和SubClassObject成員被正確恢復。

任何人都有任何想法爲什麼解析xsi:type和我做錯了什麼是錯誤的?

感謝

回答

1

這裏是我寫的

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml.Serialization; 
using System.IO; 

namespace XmlIncludeExample 
{ 
    [XmlInclude(typeof(DerivedClass))] 
    public class BaseClass 
    { 
     public string ClassName = "Base Class"; 
    } 

    public class DerivedClass : BaseClass 
    { 
     public string InheritedName = "Derived Class"; 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      string fileName = "Test.xml"; 
      string fileFullPath = Path.Combine(Path.GetTempPath(), fileName); 

      try 
      { 
       DerivedClass dc = new DerivedClass(); 

       using (FileStream fs = new FileStream(fileFullPath, FileMode.CreateNew)) 
       { 
        XmlSerializer xs = new XmlSerializer(typeof(BaseClass)); 
        xs.Serialize(fs, dc); 
       } 

       using (FileStream fs = new FileStream(fileFullPath, FileMode.Open)) 
       { 
        XmlSerializer xs = new XmlSerializer(typeof(BaseClass)); 
        DerivedClass dc2 = xs.Deserialize(fs) as DerivedClass; 
       } 
      } 
      finally 
      { 
       if (File.Exists(fileFullPath)) 
       { 
        File.Delete(fileFullPath); 
       } 
      } 
     } 
    } 
} 

這產生了以下XML

<?xml version="1.0" ?> 
- <BaseClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="DerivedClass"> 
    <ClassName>Base Class</ClassName> 
    <InheritedName>Derived Class</InheritedName> 
    </BaseClass> 

程序和它的工作

+1

的問題是有點難以閱讀,但它說「我註冊了一個事件」。那是麻煩出現的時候。將此添加到您的XmlSerializer:「xs.UnknownNode + = XsUnknownNode;」和以下事件處理程序:「 static void XsUnknownNode(object sender,XmlNodeEventArgs e) Debug.WriteLine(」Unknown {0} \ tName:{1} \ tValue:{2} \ tLine:{3} \ tPosition: {4} \ tObjectBeingDeserialized:{5}「,e.NodeType,e.Name,e.Text,e.LineNumber,e.LinePosition,e.ObjectBeingDeserialized); } 」 現在發生錯誤。我也會修改這個問題來完成它。 – ffonz 2016-09-23 09:27:16

相關問題