我看了一下字符串转义为 XML https://stackoverflow.com/questions/1132494/string-escape-into-xml并发现它非常有用。
我想做类似的事情:转义要在 XML 属性中使用的字符串。
该字符串可能包含 \r\n。
XmlWriter 类生成类似 \r\n ->
的内容。
我当前使用的解决方案包括 XmlWriter 和 StringBuilder,而且相当难看。
有什么提示吗?
Edit1:
抱歉让 LarsH 失望了,购买我的第一个方法是
public static string XmlEscapeAttribute(string unescaped)
{
XmlDocument doc = new XmlDocument();
XmlAttribute attr= doc.CreateAttribute("attr");
attr.InnerText = unescaped;
return attr.InnerXml;
}
这是行不通的。XmlEscapeAttribute("Foo\r\nBar")
将导致"Foo\r\nBar"
我使用 .NET Reflector 来了解 XmlTextWriter 如何转义属性。它使用内部的 XmlTextEncoder 类...
我目前使用的方法如下所示:
public static string XmlEscapeAttribute(string unescaped)
{
if (String.IsNullOrEmpty(unescaped)) return unescaped;
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb, settings);
writer.WriteStartElement("a");
writer.WriteAttributeString("a", unescaped);
writer.WriteEndElement();
writer.Flush();
sb.Length -= "\" />".Length;
sb.Remove(0, "<a a=\"".Length);
return sb.ToString();
}
它很丑陋而且可能很慢,但它确实有效:XmlEscapeAttribute("Foo\r\nBar")
将导致"Foo
Bar"
Edit2:
SecurityElement.Escape(unescaped);
也不行。
编辑3(最终):
使用 Lars 的所有非常有用的评论,我的最终实现如下所示:
Note: the .Replace("\r", "
").Replace("\n", "
");
有效的 XMl 不需要。这只是一个美容措施!
public static string XmlEscapeAttribute(string unescaped)
{
XmlDocument doc = new XmlDocument();
XmlAttribute attr= doc.CreateAttribute("attr");
attr.InnerText = unescaped;
// The Replace is *not* required!
return attr.InnerXml.Replace("\r", "
").Replace("\n", "
");
}
事实证明这是有效的 XML,并且将由任何符合标准的 XMl 解析器进行解析:
<response message="Thank you,
LarsH!" />