How to enable (or replace) ampersands using the .NET XML library?

Say I have the following XML:

<someRootElement>
  <someTagWithUrl>http://www.google.com/s.php&test=testing</someTagWithUrl>
</someRootElement>

The ampersand inside someTagWithUrl is invalid and should be escaped (with &amp;), but suppose I have one line with all the contents above.

How can I safely avoid ampersand so that it becomes valid XML? Can the .NET XML library ignore this? (XElement.Parse is currently throwing an exception)

I was thinking about using a regular expression to search for ampersands between tags, but I cannot get the correct syntax. (something like> (\ &) \ <as a regular expression replaces usage, but I can't figure it out).

+3
source share
3

:

&(?!quot;|apos;|amp;|lt;|gt;#x?.*?;)

& (, ). , XML:

var regex = new Regex("&(?!quot;|apos;|amp;|lt;|gt;#x?.*?;)");
string fixedXml = regex.Replace(input, "&amp;");
+2

, , XML, XML- . , , - XML/HTML- . , XmlWriter. , .

+2

, ,


>[^<]*(&)[^<]*<

+1

Source: https://habr.com/ru/post/1761211/


All Articles