podeig
podeig

Reputation: 2741

How to parse XElement with &, <, > symbols?

I have xml like this

<root>
    <text>My test is 5 > 2 & 10 < 12</text>
</root>

When I convert it to xElement

var xe = XElement.Parse(xml);

I get errors

If xml contents & so I get this error «An error occurred while parsing EntityName»

If xml contents > so I get this error «Name cannot begin with the '<' character, hexadecimal value 0x3C.»

Upvotes: 0

Views: 3376

Answers (2)

Jon
Jon

Reputation: 437604

That's because that XML is invalid, and whoever generated it is responsible. You should talk to them about fixing it, because if that's not possible you are in for a lot of pain.

Specifically, the characters &, < and > (as well as " or ' in attributes) should have been the corresponding XML entities:

<root>
    <text>My test is 5 &gt; 2 &amp; 10 &lt; 12</text>
</root>

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039238

I have xml like this

No, that's not XML. That's some random string.

You cannot parse invalid XML with XElement. In order to use an XML parser such as XElement or XDocument you need to have a valid XML first:

<root>
    <text>My test is 5 &gt; 2 &amp; 10 &lt; 12</text>
</root>

So go ahead and inform the author of this string that he needs to fix it in order to have a valid XML that could be parsed.

Upvotes: 6

Related Questions