zoukankan      html  css  js  c++  java
  • how to override serialization attributes at runtime

    At runtime, you can override serialization attributes. Here is an example:

        
    class Program
        {
            
    static void Main(string[] args)
            {
                XmlSerializer ser 
    = new XmlSerializer(typeof(Foo));
                Foo foo1 
    = (Foo)ser.Deserialize(XmlReader.Create(@"..\..\XMLFile1.xml"));
                Console.WriteLine(foo1.Bar);

                XmlRootAttribute newRoot 
    = new XmlRootAttribute();
                newRoot.ElementName 
    = "Root";
                newRoot.Namespace 
    = "http://example.org/";

                XmlAttributes myAttributes 
    = new XmlAttributes();
                myAttributes.XmlRoot 
    = newRoot;

                XmlAttributeOverrides myOverrides 
    = new XmlAttributeOverrides();
                myOverrides.Add(
    typeof(Foo), myAttributes);

                ser 
    = new XmlSerializer(typeof(Foo), myOverrides);
                Foo foo2 
    = (Foo)ser.Deserialize(XmlReader.Create(@"..\..\XMLFile2.xml"));
                Console.WriteLine(foo2.Bar);

            }
        }

        [XmlRoot(ElementName
    ="Root", Namespace="http://example.com/")]
        
    public class Foo
        {
            
    public string Bar { getset; }
        }

    The first deserialization consumes

    <?xml version="1.0" encoding="utf-8" ?>
    <Root xmlns="http://example.com/">
      
    <Bar>Baz</Bar>
    </Root>

    the second

    <?xml version="1.0" encoding="utf-8" ?>
    <Root xmlns="http://example.org/">
      
    <Bar>Baz</Bar>
    </Root>


  • 相关阅读:
    暑假第三周
    暑假第二周
    bzoj3572:[Hnoi2014]世界树
    bzoj3998:[TJOI2015]弦论
    luoguP4242树上的毒瘤
    bzoj1339/1163:[Baltic2008]Mafia
    bzoj3507:[Cqoi2014]通配符匹配
    bzoj1449:[JSOI2009]球队收益/bzoj2895:球队预算
    bzoj2243:[SDOI2011]染色
    bzoj4516:[Sdoi2016]生成魔咒
  • 原文地址:https://www.cnblogs.com/sskset/p/1743221.html
Copyright © 2011-2022 走看看