XmlSerializer是否会转义特殊字符,如&?

7

我正在尝试重构一个将其对象作为XML传输的库。虽然我认为.NET框架的XmlSerialzer可以处理序列化,但该类都有一个ToXML函数。在其中,所有字符串值都经过一个转义字符的函数处理,如&等。

XmlSerializer不会自动转义这些字符吗?

2个回答

13

是的,它确实可以。

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>

2

所有的.NET XML API自然理解XML的规则。如果必要,它们会将<转换为&lt;等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接