我是靠谱客的博主 畅快豌豆,最近开发中收集的这篇文章主要介绍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="<Sample>"> 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 = @"(?<=bw+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特殊字符转义字符,在xml中转义特殊字符的全部内容,希望文章能够帮你解决java xml特殊字符转义字符,在xml中转义特殊字符所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(45)

评论列表共有 0 条评论

立即
投稿
返回
顶部