简体   繁体   中英

How to escape quotes in xml node values in C#?

I am generating xml files for an old app.

It requires that quotes(" and ') in node values must be escaped.

But C# build-in XmlWriter can't do this, it doesn't escape quotes in node values.

I tried to replace " with " before it is passed to the node.InnerText. But after writing, it became "

for example, I want this kind of node:

<node>text contains &quot;</node>

but I either got this:

<node>text contains "</node>

or this:

<node>text contains &amp;quot;</node>

How can I escape quotes in xml node values?

The consumer of the XML is definitely wrong if it requires to preserve the quote entities in XML texts. By default, the built-in writer replaces the unnecessary entities; however, you can override this behavior by implementing a custom writer:

public class PreserveQuotesXmlTextWriter : XmlTextWriter
{
    private static readonly string[] quoteEntites = { "&apos;", "&quot;" };
    private static readonly char[] quotes = { '\'', '"' };
    private bool isInsideAttribute;

    public PreserveQuotesXmlTextWriter(string filename) : base(filename, null)
    {            
    }

    public override void WriteStartAttribute(string prefix, string localName, string ns)
    {
        isInsideAttribute = true;
        base.WriteStartAttribute(prefix, localName, ns);
    }

    private void WriteStringWithReplace(string text)
    {
        string[] textSegments = text.Split(quotes);

        if (textSegments.Length > 1)
        {
            for (int pos = -1, i = 0; i < textSegments.Length; ++i)
            {
                base.WriteString(textSegments[i]);
                pos += textSegments[i].Length + 1;

                if (pos != text.Length)
                    base.WriteRaw(text[pos] == quotes[0] ? quoteEntites[0] : quoteEntites[1]);
            }
        }
        else base.WriteString(text);
    }

    public override void WriteString(string text)
    {
        if (isInsideAttribute)
            base.WriteString(text);
        else
            WriteStringWithReplace(text);
        isInsideAttribute = false;
    }
}

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