简体   繁体   English

如何使用元素将字符串解析为XML?

[英]How to parse my string to XML with &nbsp elements?

I have string s and it looks: 我有字符串s ,它看起来:

<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; 如您所见,我想加载包含&nbsp;类的所有元素的字符串 and make it view. 并使其成为视图。 But I've got XmlException: 但是我有XmlException:

Reference to undeclared substitution to "nbsp" 引用未声明的替换为“ 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. ChrisShao提供了一个好主意:将我的字符串放在<![CDATA[标记中,但是很遗憾,它不能解决我的问题。 I have a big string with lots of tags and few big texts in which I can meet &nbsp; 我有一个很大的字符串,上面有很多标签,也没有几个大文本,我可以在其中见面&nbsp; elements. 元素。 If use System.Web.HttpUtility.HtmlDecode I lose all these elements and get " " fields. 如果使用System.Web.HttpUtility.HtmlDecode我将丢失所有这些元素并获取“”字段。

Responding to your Added section. 响应您的“ 添加”部分。 The blank ( " " ) fields you get is correct representation of &nbsp; 您获得的空白( " " )字段是&nbsp;正确表示形式&nbsp; when it is rendered. 何时渲染。 Correct encoding of &nbsp; 正确编码&nbsp; for use in xml is &#160; 在xml中使用的是&#160; [ Reference ]. [ 参考 ]。

If you really want to see &nbsp; 如果您真的想看&nbsp; instead of " " when the string loaded to XDocument , try to encode ampersand char ( & ) with &amp; 当字符串加载到XDocument ,请使用“ &amp;对“&”字符( & )进行编码,而不要使用" " . Replace &nbsp; 替换&nbsp; with &amp;nbsp; &amp;nbsp; [ Reference ]. [ 参考 ]。

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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