简体   繁体   中英

Special symbols disappear when using XDocument.Load

As I know, there are several symbols in XML, that should be replaced because they are not valid in pure form in xml:

< - &lt;
& - &amp;
> - &gt;
" - &quot;
' - &apos;

So, I'm trying to load xml document using XDocument.Load(string uri). For example I have in my xml document string that looks like this:

        <net name="&lt;const0&gt;_1"/>

But when my xml is loaded this string is represented in XDocument as

        <net name="<const0>_1"/>

I've tried to save it using xdocument.Save(string uri), but in result LT and GT symbols wasn't replaced back with & lt; and & gt; it still looks like < and >. Actually when I loaded it again no exception was thrown. It makes me confused. How could this symbols exist in saved xml file if they are not valid? How can I save my xml file with special symbols replacement? The xml file I'm reading and XDocument I want to save has a declaration with UTF-8 encoding.

Thanks!

In attributes, < and > characters are valid, that's why they are not replaced. In Text element they are always entitized:

<net>
    <name>&lt;const0&gt;_1</name>
</net>

Similarly, " and ' are allowed as Text element but will be replaced in attributes depending of the enclosing quote type.

How can I save my xml file with special symbols replacement?

You don't need to care with that. The underlying XmlWriter will do the necessary replacements.

"Q 3.23: What are the special characters in XML?

 Just five: &lt; (<), &amp; (&), &gt; (>), &quot; ("), and &apos; (')."

http://xml.silmaril.ie/specials.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM