java xml特殊字符转义字符,在xml中转义特殊字符

Using Regex, how can I escape special characters in xml attribute values?

Given the following xml as string:

"\">"

I want to get:

""

System.Security.SecurityElement.Escape function won't work as it tries to escape every special characters (including tag opening/closing angle brackets).

Talk1:

Neither the first snippet nor the second is XML. If you want to build XML in the .NET framework (with C# or another .NET language) then you can use the XmlWriter API or one of the tree models like DOM or Linq to XML implementation which then with the help of XmlWriter can be serialized to a string or file or stream. All those APIs will allow you to write or fill the attribute value with the .NET string and will take care of escaping characters like <. i don think there is an api or regexp to build a malformed string like attr=""> first and then fix it.

Talk2:

I agree that the first one is not valid xml. but it is a string, which could be translated into xml, after the special characters are encoded. Second one is valid var testXml = new System.Xml.XmlDocument(); testXml.LoadXml("");

Talk3:

As I said, use e.g. XElement node = new XElement("node", new XAttribute("attr", "")); Console.WriteLine(node); and you get well-formed XML (not valid XML, valid with XML means valid against a schema or DTD). }

Solutions1string text = "\">";

string pattern = @"(?<=\b\w+\s*=\s*"")(?="")";

string result = Regex.Replace(text, pattern, m => SecurityElement.Escape(m.Value));

Console.WriteLine(text);

Console.WriteLine(result);

Where:

?<= - positive lookbehind

\b - start the match at a word boundary

\w+ - match one or more word characters

\s* - match zero or more white-space characters

?= - positive lookahead

你可能感兴趣的:(java,xml特殊字符转义字符)