K3

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
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>


posted on 2010-05-25 07:19  K3  阅读(201)  评论(0编辑  收藏  举报