使用过滤器将Linq上的CDATA内部值提取到XML

Isa*_*son 1 c# xml linq

我正在使用此代码从XML中检索我想要的值:

IEnumerable<ForewordReview> reviews = null;
try
{
    reviews = from item in xmlDoc.Descendants("node")
              select new ForewordReview()
              {
                  PubDate = item.Element("created").ToString(),
                  Isbn = item.Element("isbn").ToString(),
                  Summary = item.Element("review").ToString()
              };
} // ...
Run Code Online (Sandbox Code Playgroud)

顺便说一下,客户端现在几乎每个带有CDATA的标签都会传递给我们,我需要提取它:

<review>
    <node>
        <created>
            <![CDATA[2012-01-23 12:40:57]]>
        </created>
        <isbn>
            <![CDATA[123456789]]>
        </isbn>
        <summary>
            <![CDATA[Teh Kittehs like to play in teh mud]]>
        </summary>
    </node>
</review>
Run Code Online (Sandbox Code Playgroud)

我已经看到了几个从CDATA标记中提取这些值的解决方案,其中一个是在LINQ语句中使用where子句:

where element.NodeType == System.Xml.XmlNodeType.CDATA
Run Code Online (Sandbox Code Playgroud)

我有点看到这里发生了什么,但我不确定这与我如何使用Linq(特别是从所选项目构建对象)有关.

我是否需要单独对select语句中的项应用此过滤器?否则,我真的不明白这将如何使用我正在使用的代码.

一如既往,我很感激帮助.

use*_*116 8

将每个投射XElement到一个string代替:

reviews = from item in xmlDoc.Descendants("node")
          select new 
          {
              PubDate = (string)item.Element("created"),
              Isbn = (string)item.Element("isbn"),
              Summary = (string)item.Element("summary")
          };
// Output:
// {
//      PubDate = 2012-01-23 12:40:57,
//      Isbn = 123456789,
//      Summary = Teh Kittehs like to play in teh mud
// }
Run Code Online (Sandbox Code Playgroud)

这也适用于其他数据类型,如int,float,DateTime,等:

reviews = from item in xmlDoc.Descendants("node")
          select new 
          {
              PubDate = (DateTime)item.Element("created")
          };
// Output:
// {
//      PubDate = 1/23/2012 12:40:57
// }
Run Code Online (Sandbox Code Playgroud)

它也适用于XAttributes.