string escape into XML-Attribute

后端 未结 3 1137
别跟我提以往
别跟我提以往 2021-02-20 11:00

I had a look at string escape into XML and found it very useful.

I would like to do a similar thing: Escape a string to be used in an XML-Attribute.

The string m

相关标签:
3条回答
  • 2021-02-20 11:12

    if it can be of any help, in several language, one uses createCDATASection to avoid all XML special characters.

    It adds something like this :

    <tag><![CDATA[ <somecontent/> ]]></tag>
    
    0 讨论(0)
  • 2021-02-20 11:14
    public static string XmlEscapeAttribute(string unescaped)
    {
        if (string.IsNullOrEmpty(unescaped))
            return unescaped;
    
        var attributeString = new XAttribute("n", unescaped).ToString();
    
        // Extract the string from the text like: n="text".
        return attributeString.Substring(3, attributeString.Length - 4);
    }
    

    This solution is similar to the one one proposed by @Mathias E. but it uses LINQ to XML rather than XmlDocument so should be faster.

    The SecurityElement.Escape() solution has a couple of problems. First it doesn't encode new lines so that has to be done as an additional step. Also, it encodes apostrophes as &apos; which is not correct in an attribute value per the XML spec.

    Inspiration for my solution came from this post.

    0 讨论(0)
  • 2021-02-20 11:23

    Modifying the solution you referenced, how about

    public static string XmlEscape(string unescaped)
    {
        XmlDocument doc = new XmlDocument();
        var node = doc.CreateAttribute("foo");
        node.InnerText = unescaped;
        return node.InnerXml;
    }
    

    All I did was change CreateElement() to CreateAttribute(). The attribute node type does have InnerText and InnerXml properties.

    I don't have the environment to test this in, but I'd be curious to know if it works.

    Update: Or more simply, use SecurityElement.Escape() as suggested in another answer to the question you linked to. This will escape quotation marks, so it's suitable for using for attribute text.

    Update 2: Please note that carriage returns and line feeds do not need to be escaped in an attribute value, in order for the XML to be well-formed. If you want them to be escaped for other reasons, you can do it using String.replace(), e.g.

    SecurityElement.Escape(unescaped).Replace("\r", "&#xD;").Replace("\n", "&#xA;");
    

    or

    return node.InnerXml.Replace("\r", "&#xD;").Replace("\n", "&#xA;");
    
    0 讨论(0)
提交回复
热议问题