CSharpBeginner
CSharpBeginner

Reputation: 611

Xml illegal characters filter

I'm using c#.
I have the follwoing xml file:

<MyXml>
    <Element>&lt;x&gt; y&lt;/p&gt<Element>
    <Element>&amp;quot;my qoute&amp;quot;<Element>
</MyXml>

How can i "filter" all the illegal characters? (<,>," etc..)
I need to write my own code like as follow:

myElement.InnerText.Replace("&lt","<");

or i have another way to do that?

Thanks!

Upvotes: 1

Views: 375

Answers (2)

Charles Mager
Charles Mager

Reputation: 26213

What you should do is fix whatever is generating this XML, as it's incorrectly inserting 'escaped' XML as text into your Element elements instead of adding child nodes.

If you can't do that, then one possible workaround is to identify those elements that are supposed to contain XML, parse the content and add the resulting elements as children:

var doc = XDocument.Parse(xml);

foreach (var element in doc.Descendants("Element"))
{
    var content = XElement.Parse("<root>" + element.Value + "</root>");
    element.ReplaceNodes(content.Nodes());
}

Upvotes: 1

tjhazel
tjhazel

Reputation: 902

XmlElement.InnerText is escaped for you. A similar question is answered at String escape into XML

Upvotes: 1

Related Questions