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 = @"(?<=\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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值