2009-08-12 9 views
5

Próbuję refaktoryzować bibliotekę, która transmituje obiekt jako XML. Chociaż wydaje mi się, że XmlSerialzer w .NET Framework może obsłużyć serializację, wszystkie klasy mają funkcję ToXML. W nim wszystkie wartości łańcuchowe są wprowadzane przez funkcję, która wymyka się ze znaków , podobnie jak & i podobne.Czy XmlSerializer ucieka od znaków specjalnych, takich jak &?

Czy XmlSerializer nie uniknie automatycznie tych znaków?

Odpowiedz

10

Tak jest.

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); 
      } 
     } 
    } 
} 

powraca

<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

Wszystkie API .NET XML w naturalny sposób rozumieją zasady XML. W razie potrzeby zmienią one < w &lt; itd.

Powiązane problemy