简体   繁体   中英

xml serialization encoding “&” character

I am converting an object into xml string and then into an escaped string.

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

How can I avoid getting &amp; in xmlstring variable.

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

I am looking for output something like this:

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

You can use Unicode equivalent character ie decimal or hex, & or & instead.

"B & A Auto" => "B &#038 A Auto";

You can parse your string, convert amps to their unicode equivalence and then escape those.

No, you can not. The & is a special character in XML and used for escaping other characters.

Escaped character in XML

' = &apos;

< = &lt;

> = &gt;

& = &amp;

" = &quot;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM