1

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!

CSharpBeginner
  • 601
  • 2
  • 7
  • 22
  • Why do you think these are illegal characters instead of *the valid XML representation* of the special characters? What are you trying to do? How did these characters end in there? Did you use HTML encoding on an XML or HTML snippet perhaps? How was this file generated? You should fix the code that generates the file if that isn't what you expected – Panagiotis Kanavos Jun 30 '16 at 15:24
  • I have another application that create me the .xml files..i want to replace the xml file instead &lt to < etc.. "<" its a legal character in the xml value? if so, i dont know why the another appication write &lt instead of <..i have no the another application code.. – CSharpBeginner Jun 30 '16 at 15:26
  • Obviously, otherwise you wouldn't be able to write ``. If `Element` is allowed to contain children according to its schema, the generating application has a bug – Panagiotis Kanavos Jun 30 '16 at 15:28
  • that isn't the real .xml file.. i just take the text as example – CSharpBeginner Jun 30 '16 at 15:29

2 Answers2

1

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

Community
  • 1
  • 1
tjhazel
  • 772
  • 7
  • 12
  • Thanks, but at the answer they does the "Reverse" way, that takes "<" and convert it to "&lt" i want to take "&lt" and to change it to "<" at my .xml file – CSharpBeginner Jun 30 '16 at 15:36
1

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());
}
Charles Mager
  • 25,735
  • 2
  • 35
  • 45