【问题标题】:Read CDATA section based on where clause using LINQ使用 LINQ 读取基于 where 子句的 CDATA 部分
【发布时间】:2012-06-08 11:36:15
【问题描述】:

我正在尝试根据 where 子句读取 xml 节点的 CDATA 部分。

<Book>
  <BookItem ISBN="SKS84747"><![CDATA[20]]> </BookItem>
  <BookItem ISBN="LHKGOI84747"><![CDATA[50]]> </BookItem>
  <BookItem ISBN="PUOT84747"><![CDATA[20]]> </BookItem>
</Book>

这段代码给了我所有的 CDATA 部分,

var value = from v in x.Descendants("BookItem").OfType<XCData>()
                                select (string)v.Value;

如何根据 ISBN 放置 where 子句? 如何使用 LINQ to XML 读取此 CDATA。

【问题讨论】:

  • HashItem 是 BookItem 的错字,还是我漏掉了什么?

标签: c# linq-to-xml cdata


【解决方案1】:
var value = x.DescendantNodes().OfType<XCData>()
                .Where(m => m.Parent.Name == "BookItem" && m.Parent.Attribute("ISBN").Value == "PUOT84747")
                .ToList();

在 ToList() 之前

.Select(cdata => cdata.Value.ToString());

【讨论】:

    【解决方案2】:
    var xml = Resource1.String1;
    var doc = XDocument.Parse(xml);
    var isbn = "SKS84747";
    var query = string.Format("BookItem[@ISBN='{0}']", isbn);
    var book = doc.Root.XPathSelectElement(query);
    
    if (book != null)
        Console.WriteLine(book.Value);
    

    var book =
        doc.Root.Descendants("BookItem").Where(
            x => x.Attribute("ISBN") != null && x.Attribute("ISBN").Value == isbn).Select(x => x.Value).
            FirstOrDefault();
    

    var book = (from item in doc.Root.Descendants("BookItem")
                where item.Attributes("ISBN").Any() && item.Attribute("ISBN").Value == isbn
                select item.Value).FirstOrDefault();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-02
      • 1970-01-01
      相关资源
      最近更新 更多