在C#德code CDATA节code、CDATA

由网友(唯以深情久伴长歌)分享简介:我有一点XML如下:我用 curXmlNode.SelectSingleNode(说明)访问它。的InnerTe...

我有一点XML如下:

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

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

rn      This is a "description"rn      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.

阅读全文

相关推荐

最新文章