本文介绍了在C#德code CDATA节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一点XML如下:

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

我用 curXmlNode.SelectSingleNode(说明)访问它。的InnerText ,但显示的值返回

\r\n      This is a "description"\r\n      that I have formatted

而不是

This is a "description" that I have formatted.

有一个简单的方法来获得那​​种输出的CDATA节?离开实际的CDATA标记出来,似乎有它原路返回。

Is there a simple way to get that sort of output from a CDATA section? Leaving the actual CDATA tag out seems to have it return the same way.

推荐答案

您可以使用LINQ阅读CDATA。

You can use Linq to read CDATA.

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

这是很容易得到的价值这种方式。

It's very easy to get the Value this way.

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

Here's a good overview on MSDN: http://msdn.microsoft.com/en-us/library/bb308960.aspx

有关.NET 2.0中,你可能只需要通过正则表达式来传递:

for .NET 2.0, you probably just have to pass it through 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正在返回显著空白。

that trims your node value, replaces newlines with empty, and replaces 1+ whitespaces with one space. I don't think there's any other way to do it, considering the CDATA is returning significant whitespace.

这篇关于在C#德code CDATA节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:44