XML序列化,動態修改特性元數據內容

通過爲XML序列化添加XmlRootAttribute

XmlRootAttribute root = new XmlRootAttribute();
root.ElementName = "修改名稱";
XmlSerializer mySerializer = new XmlSerializer(typeof(Data), root);

 

二、一般節點的ElementName的修改

XmlElementAttribute myElementAttribute = new XmlElementAttribute();
myElementAttribute.ElementName= "修改名稱";
XmlAttributes myAttributes = new XmlAttributes();
myAttributes.XmlElements.Add(myElementAttribute);

XmlAttributeOverrides myOverrides = new XmlAttributeOverrides();

myOverrides.Add(typeof(Data), "lsarea", myAttributes);

XmlSerializer mySerializer = new XmlSerializer(typeof(Data), myOverrides);

 

 

 

 

 

例子:

    Data fdadf = new Data();

            area test = new area();
            test.areaid = "100";
            item it = new item();
            it.remark = "說明1";
            it.PK.intervaltype = "1";
            it.PK.key = "fd";

            item it2 = new item();
            it2.remark = "說明2";
            test.lsItem.Add(it);
            test.lsItem.Add(it2);

            fdadf.lsarea.Add(test);

            XmlSerializerNamespaces xsns = new XmlSerializerNamespaces();
            xsns.Add(string.Empty, string.Empty);
  
     StreamWriter writer = new StreamWriter("books.xml");
       mySerializer.Serialize(writer, fdadf);

例實體:

 [XmlType("DataGrid")]
    public class Data
    {
        public Data()
        {
            lsarea = new List<area>();
        }

        [XmlElement("area")]
        public List<area> lsarea;
    }

    [XmlType("area")]
    public class area
    {

        public area()
        {
            areaid = string.Empty;
            lsItem = new List<item>();
        }
        [XmlElement(Order = 1, ElementName = "areaid")]
        public string areaid
        {
            get;
            set;
        }

        [XmlElement(Order = 2, ElementName = "Item")]
        public List<item> lsItem;


    }
    [XmlType("item")]
    public class item
    {
        public item()
        {
            PK = new nid();
        }

 

        [XmlElement("PK")]
        public nid PK
        {
            get;
            set;
        }

        [XmlElement("value")]
        public string value
        {
            get;
            set;
        }
        [XmlElement("remark")]
        public string remark
        {
            get;
            set;
        }
    }


    [XmlType("PK")]
    public class nid
    {

        [XmlElement("key")]
        public string key
        {
            get;
            set;
        }

        [XmlElement("intervaltype")]
        public string intervaltype
        {
            get;
            set;
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章