我查看了字符串转义到 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 类...
我的方法我目前正在使用这样的 lokks:
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"
编辑2:
SecurityElement.Escape(unescaped);
也不起作用。
编辑3(最终):
使用来自 Lars 的所有非常有用的评论,我的最终实现如下所示:
注意:.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!" />