简体   繁体   中英

How to parse my string to XML with &nbsp elements?

I have string s and it looks:

<root><p>hello world</p>&nbsp;my name is!</root>

I have next code:

try
{
    m_Content = XDocument.Load(new StringReader(s));
}
catch (XmlException ex)
{
    ex.Data["myerror"] = s;

    throw;
}

As you see, I want to load string with all elements like &nbsp; and make it view. But I've got XmlException:

Reference to undeclared substitution to "nbsp"

Any ideas how to do it right?

Added

ChrisShao offered a good idea: put my string in <![CDATA[ tag, but unfortunately it doesnt solve my problem. I have a big string with lots of tags and few big texts in which I can meet &nbsp; elements. If use System.Web.HttpUtility.HtmlDecode I lose all these elements and get " " fields.

Responding to your Added section. The blank ( " " ) fields you get is correct representation of &nbsp; when it is rendered. Correct encoding of &nbsp; for use in xml is &#160; [ Reference ].

If you really want to see &nbsp; instead of " " when the string loaded to XDocument , try to encode ampersand char ( & ) with &amp; . Replace &nbsp; with &amp;nbsp; [ Reference ].

使用System.Web.HttpUtility.HtmlDecode或System.Net.WebUtility.HtmlDecode

我认为您应该将字符串放入CDATA块中,如下所示:

<root><![CDATA[<p>hello world</p>&nbsp;my name is!]]></root>

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