XML节点ElementName的动态修改

一、根节点的ElementName的修改

通过为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;
        }
    }

posted @ 2010-10-25 19:39  sunfny  阅读(1299)  评论(0编辑  收藏  举报