xml序列化编码“&”字符

时间:2019-07-22 17:48:21

标签: c# xml-serialization

我正在将一个对象转换为xml字符串,然后转换为转义的字符串。

public class Program
{
    public static void Main(string[] args)
    {
        BankDetails details = new BankDetails();

        var xmlstring = ToXmlString(details);
        var escaped = SecurityElement.Escape(xmlstring);
    }

    private static string ToXmlString<T>(T input)
    {
        XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        var xml = "";
        ns.Add("", "");

        using (var sww = new StringWriter())
        {
            using (XmlWriter writer = XmlWriter.Create(sww, new XmlWriterSettings()
            {
                OmitXmlDeclaration = true
            }))
            {
                xsSubmit.Serialize(writer, input, ns);
                xml = sww.ToString();
            }
        }

        return xml;
    }
}

public class BankDetails
{
    public string MemberName = "B & A Auto";
}

如何避免在&amp;变量中获取xmlstring

<BankDetails><MemberName>B &amp; A Auto</MemberName></BankDetails>

我正在寻找类似这样的输出:

xmlstring = //<BankDetails><MemberName>B & A Auto</MemberName></BankDetails>
//and then
escaped = //&lt;BankDetails&gt;&lt;MemberName&gt;B &amp; A Auto&lt;/MemberName&gt;&lt;/BankDetails&gt;

Working Fiddle

2 个答案:

答案 0 :(得分:0)

您可以使用Unicode等效字符,即十进制或十六进制,&或&代替。

“ B&A Auto” =>“ B&#038 A Auto”;

您可以解析字符串,将安培转换为它们的unicode等效项,然后对其进行转义。

答案 1 :(得分:0)

不,您不能。 &是XML中的特殊字符,用于转义其他字符。

XML中的转义字符

'=‘

<=&lt;

> =&gt;

&=&amp;

“ =&quot;