为什么这个Linq to XML查询不起作用

时间:2010-09-14 16:40:03

标签: c# linq linq-to-xml

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 个答案:

答案 0 :(得分:3)

编辑:嗯......之前我没有意识到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(...)

如果你也想。

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