如何在C#中的xml节点值中转义引号?

时间:2015-11-02 11:59:12

标签: c# xml

我正在为旧应用生成xml文件。

它要求必须转义节点值中的引号(“和”)。

但是C#内置XmlWriter不能这样做,它不会在节点值中转义引号。

我尝试将"替换为",然后再将其传递给node.InnerText。 但写完后,它变成了"

例如,我想要这种节点:

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

但我得到了这个:

<node>text contains "</node>

或者这个:

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

如何在xml节点值中转义引号?

1 个答案:

答案 0 :(得分:1)

如果需要在XML文本中保留引用实体,那么XML的使用者肯定是错误的。默认情况下,内置编写器替换不必要的实体;但是,您可以通过实现自定义编写器来覆盖此行为:

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