C#的XML序列化和反序列化1

3.1 從可串行化的類中定製XML串行化
     1.格式化XML文檔元素

     [XmlRoot(ElementName = " Pupil " , Namespace = " urn:MyNamespace " )]
    
public class Student
    
{
        
// 則生成XML文檔中,根元素<Pupil xmlns="urn:MyNamespace">
     }

    
     2.格式化XML元素

         [XmlElement(ElementName = " FullName " , Namespace = " urn:OtherNamespace " )]
        
public string Name
        
{
            
get { return name; }
            
set { name = value; }
         }

    
         生成XML如下:

<? xml version = " 1.0 " encoding = " utf-8 " ?>
< Pupil xmlns:xsd = " http://www.w3.org/2001/XMLSchema "
        xmlns:d1p1
= " urn:OtherNamespace " >
  
< d1p1:FullName > Thomas Smith </ d1p1:FullName >     
</ Pupil >

         這裏的d1p1是自動生成的,在標題4,有辦法自己指定Namespace前綴。
         
     3.格式化XML屬性

         [XmlAttribute(AttributeName = " StudentNumber " , Namespace = " urn:MyNamespace " )]
        
public string Name
        
{
            
get { return name; }
            
set { name = value; }
         }


         同樣還是Name屬性,這次是使用XmlAttribute標籤,生成XML如下:

<? xml version = " 1.0 " encoding = " utf-8 " ?>
< Pupil xmlns:xsd = " http://www.w3.org/2001/XMLSchema "
        xmlns:d1p1
= " urn:OtherNamespace "
        d1p1:Name
= " Thomas Smith " >
</ Pupil >

         XML屬性在空間利用率上比XML元素略高一些。
        
     4.爲元素/屬性設計限定的命名空間
         使用XmlSerializer的Serialize方法重載,額外帶一個XmlSerializerNamespace參數,指定這個命名空間前綴

         public void SerializeIt( string filename)
        
{
            
// 自定義命名空間
             XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
             ns.Add(
" xsd " , " http://www.w3.org/2001/XMLSchema " );
             ns.Add(
" xsi " , " http://www.w3.org/2001/XMLSchema-instance " );
             ns.Add(
" otherNS " , " urn:OtherNamespace " );

             XmlSerializer serializer
= new XmlSerializer( typeof (Book));
             StreamWriter writer
= new StreamWriter(filename);
             Book myBook
= new Book();

            
// 使用Serialize重載方法
             serializer.Serialize(writer, myBook, ns);
             writer.Close();
         }


         從而生成完全自定義的XML:

<? xml version = " 1.0 " encoding = " utf-8 " ?>
< Pupil xmlns:xsd = " http://www.w3.org/2001/XMLSchema "
        xmlns:otherNS
= " urn:OtherNamespace "
         xmlns:xsi
= " http://www.w3.org/2001/XMLSchema-instance "
         otherNS:StudentNumber
= " 8007 " xmlns = " urn:MyNamespace " >
    
< otherNS:FullName > Thomas Smith </ otherNS:FullName >
</ Pupil >
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章