代码之家  ›  专栏  ›  技术社区  ›  Luke101

为什么这个linq-to-xml查询不工作

  •  2
  • Luke101  · 技术社区  · 15 年前
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml.Linq;
    
    namespace ConsoleApplication2
    {
        class Program
        {
            static void Main(string[] args)
            {
                XDocument xDocument = new XDocument(
                    new XElement("BookParticipants",
                    new XElement("BookParticipant",
                    new XAttribute("type", "Author"),
                    new XElement("FirstName", "Joe", new XElement("name", 
                        new XElement("noot", "the"),
                        new XElement("iscool", "yes"))),
                    new XElement("LastName", "Rattz")),
                    new XElement("BookParticipant",
                    new XAttribute("type", "Editor"),
                    new XElement("FirstName", "Ewan", new XElement("name", 
                        new XElement("noot", "the"),
                        new XElement("iscool", "yes"))),
                    new XElement("LastName", "Buckingham"))));
    
    
                xDocument.Descendants("BookParticipants").Where(x => (string)x.Element("FirstName") == "Joe").Remove();
                Console.WriteLine(xDocument);
    
            }
        }
    }
    

    我正在尝试使用WHERE子句删除joe元素。但这不起作用。是否可以使用WHERE子句删除元素?

    1 回复  |  直到 15 年前
        1
  •  3
  •   Jon Skeet    15 年前

    编辑:嗯…我不知道 Remove extension method 之前。

    问题是,当您将元素转换为字符串时,它会连接 全部的 后代文本节点…所以“joe”元素的值实际上是“joe the yet”。

    你只想 直接的 子文本节点。坦率地说,如果名称是在属性中而不是作为内容,这会更容易,但它仍然是可行的…

    另外,你正在寻找 FirstName 直接在下面的元素 BookParticipants 而不是 BookParticipant .

    这是可行的,虽然不太愉快:

    xDocument.Descendants("BookParticipants")
             .Elements()
             .Where(x => x.Elements("FirstName")
                          .Nodes()
                          .OfType<XText>()
                          .Any(t => t.Value== "Joe"))
             .Remove();
    

    你可以把第一位改成

    xDocument.Descendants("BookParticipant")
             .Where(...)
    

    如果你愿意的话。

    (同样,如果您可以将属性用于字符串值,而不是元素中的内容,这将使生活更容易。)

    推荐文章