簡體   English   中英

Xml列表序列化和節點類型名稱

[英]Xml List Serialization and Node Type Names

我在這里遇到了多個問題和答案,但都沒有針對我的情況。

我有一個帶有多個擴展類的“​​實體”類。 我希望序列化能夠打入列表,並理解並使用每個項目的類型作為節點名稱。

現在,我可以使用注釋掉的內容(在主類中定義每個數組項,並通過使用[XmlArrayItem(“ Subclass1”,typeof(subclass1)]]定義其名稱,但我想將所有定義保留在其子類中,將有太多的子類來定義主實體類中的所有內容...總有辦法實現嗎?

我嘗試對子類使用[XmlType(TypeName =“ ...”)],依此類推,但沒有用。

[Serializable]
[XmlInclude(typeof(Subclass1))]
[XmlRoot("Entity")]
public class Entity{

    [XmlArray("CausedBy")]
    //[XmlArrayItem("Subclass1", typeof(subclass1))]
    //[XmlArrayItem("Sublcass2", typeof(Subclass2))]
    public List<Entity> CausedBy { get; set; }

}

[Serializable]
[XmlRoot("Subclass1")]
[XmlInclude(typeof(Subclass2))]
public class Subclass1:Entity{
    //Code...
}

[Serializable]
[XmlRoot("Subclass2")]
public class Subclass2:Subclass1{
  //Code...
}

創建實體並將Subclass1和Subclass2添加到列表“ CausedBy”類后,序列化上述代碼將導致以下結果:

<Entity>
  <CausedBy>
    <Entity ... xsi:type="SubClass1" />
    <Entity ... xsi:type="SubClass2" />
   </CausedBy>
<Entity>

我希望輸出顯示:

 <Entity>
      <CausedBy>
        <SubClass1 .../>
        <SubClass2 .../>
       </CausedBy>
    <Entity>

由於我完全沒有讀懂開頭的問題,因此這里是一個新答案(有點像tl; dr,因此您始終可以跳到結尾並點擊鏈接):

無法使內置的序列化程序類起作用,因為您不希望添加它需要能夠運行的屬性。 您唯一的選擇是自己上課,但是這不需要聽起來那么乏味。 幾年前,我在虛擬模式下使用DataGridView遇到了類似的問題,並制作了一個通用虛擬化程序,可用於虛擬化要顯示的數據。 它使用了一個自定義屬性:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class showColumnAttribute : System.Attribute
{
    ///<summary>Optional display format for column</summary>
    public string Format;
    ///<summary>Optional Header string for column<para>Defaults to propety name</para></summary>
    public string Title;
    ///<summary>Optional column edit flag - defaults to false</summary>
    public bool ReadOnly;
    ///<summary>Optional column width</summary>
    public int Width;
    ///<summary>
    ///Marks public properties that are to be displayed in columns
    ///</summary>
    public showColumnAttribute()
    {
        Format = String.Empty;
        Title = String.Empty;
        ReadOnly = false;
        Width = 0;
    }
}

還有一個構造函數:

    ///<summary>
    ///Extracts the properties of the supplied type that are to be displayed
    ///<para>The type must be a class or an InvalidOperationException will be thrown</para>
    ///</summary>
    public Virtualiser(Type t)
    {
        if (!t.IsClass)
            throw new InvalidOperationException("Supplied type is not a class");

        List<VirtualColumnInfo> definedColumns = new List<VirtualColumnInfo>();
        PropertyInfo[] ps = t.GetProperties();
        MethodInfo mg, ms;

        for (int i = 0; i < ps.Length; i++)
        {
            Object[] attr = ps[i].GetCustomAttributes(true);

            if (attr.Length > 0)
            {
                foreach (var a in attr)
                {
                    showColumnAttribute ca = a as showColumnAttribute;
                    if (ca != null)
                    {
                        mg = ps[i].GetGetMethod();
                        if (mg != null)
                        {
                            ms = ps[i].GetSetMethod();
                            definedColumns.Add
                            (
                                new VirtualColumnInfo
                                (
                                    ps[i].Name, ca.Width, ca.ReadOnly, ca.Title == String.Empty ? ps[i].Name : ca.Title, 
                                    ca.Format, mg, ms
                                )
                            );
                        }
                        break;
                    }
                }
            }
        }
        if (definedColumns.Count > 0)
            columns = definedColumns.ToArray();
    }

這將提取類的公共屬性,並將帶有標記的項目作為列以及標題,格式等提供給DataGridView。

所有這些(以及其余缺少的代碼)的結果是,只需標記公共屬性並為給定類型調用一次虛擬器,就可以在dataGridView中將任何類型虛擬化:

    #region Virtualisation
    static readonly Virtualiser Virtual = new Virtualiser(typeof(UserRecord));
    [XmlIgnore] // just in case!
    public static int ColumnCount { get { return Virtual.ColumnCount; } }
    public static VirtualColumnInfo ColumnInfo(int column)
    {
        return Virtual.ColumnInfo(column);
    }

    public Object GetItem(int column)
    {
        return Virtual.GetItem(column, this);
    }
    /*
    ** The supplied item should be a string - it is up to this method to supply a valid value to the property
    ** setter (this is the simplest place to determine what this is and how it can be derived from a string).
    */
    public void SetItem(int column, Object item)
    {
        String v = item as String;
        int t = 0;
        if (v == null)
            return;
        switch (Virtual.GetColumnPropertyName(column))
        {
            case "DisplayNumber":
                if (!int.TryParse(v, out t))
                    t = 0;

                item = t;
                break;
        }
        try
        {
            Virtual.SetItem(column, this, item);
        }
        catch { }
    }
    #endregion

可以通過創建一些從類數據派生的公共屬性來自動指定列數,它們的屬性和順序:

        #region Display columns
    [showColumn(ReadOnly = true, Width = 100, Title = "Identification")]
    public String DisplayIdent
    {
        get
        {
            return ident;
        }
        set
        {
            ident = value;
        }

    }
    [showColumn(Width = 70, Title = "Number on Roll")]
    public int DisplayNumber
    {
        get
        {
            return number;
        }
        set
        {
            number = value;
        }
    }
    [showColumn(Width = -100, Title = "Name")]
    public string DisplayName
    {
        get
        {
            return name == String.Empty ? "??" : name;
        }
        set
        {
            name = value;
        }
    }
    #endregion

這將虛擬化dataGridView的任何類以顯示和編輯數據,並且我多年來使用了很多次,提取屬性以顯示的正是XML序列化所必需的,實際上,它具有許多相同的特性。

我打算改用這種方法來完成XML序列化的相同工作,但是有人已經在https://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=474453上做到了,希望您可以使用解決您的問題的方法。

這對我有用:

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Entity entity = new Entity();
        entity.CausedBy = new List<Entity>();
        entity.CausedBy.Add(new Subclass1());
        entity.CausedBy.Add(new Subclass2());
        entity.CausedBy.Add(new Subclass2());
        entity.CausedBy.Add(new Subclass1());
        entity.CausedBy.Add(new Subclass1());
        entity.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Test.txt"));
    }
}
[Serializable]
[XmlRoot("Entity")]
public class Entity
{
    [XmlArray("CausedBy")]
    [XmlArrayItem("SubClass1", typeof(Subclass1))]
    [XmlArrayItem("SubClass2", typeof(Subclass2))]
    public List<Entity> CausedBy { get; set; }

}

[Serializable]
[XmlRoot("Subclass1")]
public class Subclass1 : Entity
{
    [XmlIgnore]
    String t = DateTime.Now.ToShortDateString();

    public String SubClass1Item { get { return "Test1 " + t; } set { } }
}

[Serializable]
[XmlRoot("Subclass2")]
public class Subclass2 : Entity
{
    [XmlIgnore]
    String t = DateTime.Now.ToString();

    public String SubClass2Item { get { return "Test2 " + t; } set { } }
}

它產生:

<Entity xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <CausedBy>
    <SubClass1>
      <SubClass1Item>Test1 20/09/2017</SubClass1Item>
    </SubClass1>
    <SubClass2>
      <SubClass2Item>Test2 20/09/2017 01:06:55</SubClass2Item>
    </SubClass2>
    <SubClass2>
      <SubClass2Item>Test2 20/09/2017 01:06:55</SubClass2Item>
    </SubClass2>
    <SubClass1>
      <SubClass1Item>Test1 20/09/2017</SubClass1Item>
    </SubClass1>
    <SubClass1>
      <SubClass1Item>Test1 20/09/2017</SubClass1Item>
    </SubClass1>
  </CausedBy>
</Entity>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM