我试图在.NET(C#)中的字符串中删除XML实体,但我似乎没有让它正常工作.
例如,如果我有字符串AT&T,则应将其翻译为AT&T.
一种方法是使用HttpUtility.HtmlDecode(),但这是用于HTML.
所以我有两个问题:
使用HttpUtility.HtmlDecode()解码XML实体是否安全?
我如何使用XmlReader(或类似的东西)来做到这一点?我尝试了以下,但总是返回一个空字符串:
static string ReplaceEscapes(string text)
{
StringReader reader = new StringReader(text);
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader xmlReader = XmlReader.Create(reader, settings))
{
return xmlReader.ReadString();
}
}
Run Code Online (Sandbox Code Playgroud)我看了一下XML转义的字符串,发现它非常有用.
我想做类似的事情:转义要在XML-Attribute中使用的字符串.
该字符串可能包含\ r \n.XmlWriter类产生类似\ r \n - >
我目前使用的解决方案包括XmlWriter和StringBuilder,而且非常难看.
任何提示?
编辑1:
抱歉让LarsH失望,买我的第一个方法是
public static string XmlEscapeAttribute(string unescaped)
{
XmlDocument doc = new XmlDocument();
XmlAttribute attr= doc.CreateAttribute("attr");
attr.InnerText = unescaped;
return attr.InnerXml;
}
Run Code Online (Sandbox Code Playgroud)
这是行不通的.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, …Run Code Online (Sandbox Code Playgroud) 我的问题与此类似:WPF生成TextBlock内联,但我没有足够的声誉来评论.这是附加的属性类:
public class Attached
{
public static readonly DependencyProperty FormattedTextProperty = DependencyProperty.RegisterAttached(
"FormattedText",
typeof(string),
typeof(TextBlock),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsMeasure));
public static void SetFormattedText(DependencyObject textBlock, string value)
{
textBlock.SetValue(FormattedTextProperty, value);
}
public static string GetFormattedText(DependencyObject textBlock)
{
return (string)textBlock.GetValue(FormattedTextProperty);
}
private static void FormattedTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBlock = d as TextBlock;
if (textBlock == null)
{
return;
}
var formattedText = (string)e.NewValue ?? string.Empty;
formattedText = string.Format("<Span xml:space=\"preserve\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">{0}</Span>", formattedText);
textBlock.Inlines.Clear();
using (var xmlReader = XmlReader.Create(new StringReader(formattedText))) …Run Code Online (Sandbox Code Playgroud)