【问题标题】:Why is this Linq to XML query not working为什么此 Linq to XML 查询不起作用
【发布时间】:2010-09-14 16:40:02
【问题描述】:
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 子句删除元素?

【问题讨论】:

  • “这不起作用”到底是什么意思?编译器错误?例外?出乎意料的结果?
  • 当我运行代码时,Joe 元素仍然存在。它没有被删除。这里有什么想法吗?

标签: c# linq linq-to-xml


【解决方案1】:

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

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

您只需要 direct 子文本节点。坦率地说,如果名称在属性中而不是内容中会更容易,但它仍然应该是可行的......

此外,您正在寻找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(...)

如果你愿意,也可以。

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

【讨论】:

  • 天啊。这行得通..你是为微软工作还是什么的。我现在知道我有很多东西要了解 linq 本身。谢谢--请问您阅读了哪些书来了解linq to xml?
  • @Luke101:不,我不为 MS 工作。我在 Google 工作 :) 至于看书……我用 C# 深入地写了关于 LINQ 的文章,所以我当时大部分时间都是用文档自学的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 1970-01-01
  • 2012-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多