2009-08-12 24 views
5

我試圖重構一個將它的對象作爲XML傳輸的庫。儘管我認爲.NET Framework的XmlSerialzer可以處理序列化,但該類都具有ToXML函數。其中所有的字符串值都會通過一個函數進行轉義,如&等字符 。XmlSerializer是否會轉義特殊字符,例如&?

XmlSerializer不會自動轉義那些類型的字符嗎?

回答

10

是的。

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Xml.Serialization; 
using System.Xml; 

namespace TestXmlSerialiser 
{ 
    public class Person 
    { 
     public string Name; 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      Person person = new Person(); 
      person.Name = "Jack & Jill"; 

      XmlSerializer ser = new XmlSerializer(typeof(Person)); 

      XmlWriterSettings settings = new XmlWriterSettings(); 
      settings.Indent = true; 

      using (XmlWriter writer = XmlWriter.Create(Console.Out, settings)) 
      { 
       ser.Serialize(writer, person); 
      } 
     } 
    } 
} 

回報

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Name>Jack &amp; Jill</Name> 
</Person> 
1

所有的.NET XML API自然都理解XML的規則。如有必要,他們會將<更改爲&lt;等。