【问题标题】:Does the XmlSerializer escape special chars like &?XmlSerializer 是否会转义像 & 这样的特殊字符?
【发布时间】:2009-08-12 13:31:59
【问题描述】:

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

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

【问题讨论】:

    标签: c# xml serialization


    【解决方案1】:

    是的。

    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 的规则。如有必要,他们会将&amp;lt; 更改为&amp;lt; 等。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-18
        • 1970-01-01
        • 1970-01-01
        • 2020-10-25
        • 1970-01-01
        • 2015-07-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多