gpt4 book ai didi

c# - 在 C# 中解码 CDATA 部分

转载 作者:可可西里 更新时间:2023-11-01 08:31:03 25 4
gpt4 key购买 nike

我有一些 XML 如下:

<section>
<description>
<![CDATA[
This is a "description"
that I have formatted
]]>
</description>
</section>

我正在使用 curXmlNode.SelectSingleNode("description").InnerText 访问它,但值返回

\r\n      This is a "description"\r\n      that I have formatted
而不是
This is a "description" that I have formatted.

有没有一种简单的方法可以从 CDATA 部分获得这种输出?将实际的 CDATA 标记留在外面似乎让它以相同的方式返回。

最佳答案

您可以使用 Linq 读取 CDATA。

XDocument xdoc = XDocument.Load("YourXml.xml");
xDoc.DescendantNodes().OfType<XCData>().Count();

通过这种方式获取值非常容易。

这是 MSDN 上的一个很好的概述:http://msdn.microsoft.com/en-us/library/bb308960.aspx

对于 .NET 2.0,您可能只需要通过 Regex 传递它:

     string xml = @"<section>
<description>
<![CDATA[
This is a ""description""
that I have formatted
]]>
</description>
</section>";

XPathDocument xDoc = new XPathDocument(new StringReader(xml.Trim()));
XPathNavigator nav = xDoc.CreateNavigator();
XPathNavigator descriptionNode =
nav.SelectSingleNode("/section/description");

string desiredValue =
Regex.Replace(descriptionNode.Value
.Replace(Environment.NewLine, String.Empty)
.Trim(),
@"\s+", " ");

修剪您的节点值,将换行符替换为空行,并将 1+ 个空格替换为一个空格。考虑到 CDATA 正在返回重要的空白,我认为没有任何其他方法可以做到这一点。

关于c# - 在 C# 中解码 CDATA 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1236785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com