переход строки в XML-атрибут

Я взглянул на преобразование строки в XML и нашел его очень полезным.

Я хотел бы сделать то же самое: экранировать строку, которая будет использоваться в XML-атрибут.

Строка может содержать \ r \ n. The XmlWriter class produces something like \r\n ->

The solution I'm currently using includes the XmlWriter and a StringBuilder and is rather ugly.

Any hints?

Edit1:
Sorry to disappoint LarsH, buy my first approach was

public static string XmlEscapeAttribute(string unescaped)
{
    XmlDocument doc = new XmlDocument();
    XmlAttribute attr= doc.CreateAttribute("attr");
    attr.InnerText = unescaped;
    return attr.InnerXml;
}

It does not work. XmlEscapeAttribute("Foo\r\nBar") will result in "Foo\r\nBar"

I used the .NET Reflector, to find out how the XmlTextWriter escapes Attributes. It uses the XmlTextEncoder class which is internal...

My method I'm currently usig lokks like this:

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, "

It's ugly and probably slow, but it does work: XmlEscapeAttribute("Foo\r\nBar") will result in "Foo Bar"

Edit2:

SecurityElement.Escape(unescaped);

does not work either.

Edit3 (final):

Using all the very useful comments from Lars, my final implementation looks like this:

Note: the .Replace("\r", " ").Replace("\n", " "); is not required for valid XMl. It is a cosmetic measure only!

    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", "
");
    }

As it turns out this is valid XML and will be parsed by any standard compliant XMl-parser:


9
задан Community 23 May 2017 в 12:23
поделиться