【问题标题】:C# LINQ to XML: number of elements, that have two same attributes?C# LINQ to XML:具有两个相同属性的元素数量?
【发布时间】:2012-11-07 17:42:44
【问题描述】:

我有这样的事情:

<Books>
    <Book>
        <Number>
        <Title>
        <Author>
        <NumberOfCopies>
    </Book>
</Books>

NumberOfCopies 元素表示图书馆拥有同一本书的相同副本数。 (相同的书籍=相同的作者,相同的标题)。 Number 元素对于每本书都不同,用于将它们存储在图书馆中。

当我添加一本新书时,我想知道图书馆有多少册。(int number)怎么做?

XDocument doc = XDocument.Load("books.xml");
var q = from x in doc.Descendants("Books")
        where x.Element("Author").Value == newBook.Author
              && x.Element("Title").Value == newBook.Title
        select x;

int number = (int)q;

这不起作用。我做错了什么?

【问题讨论】:

  • 请向我们展示实际的 XML - 我们无法在这里说出结构。 (特别是,您谈到了属性,但我们看不到任何...)

标签: c# xml linq


【解决方案1】:

怀疑你想要:

var book = doc.Descendants("Book") // Note Book, not Books
              .Where(x => x.Element("Author").Value == newBook.Author &&
                          x.Element("Title").Value == newBook.Title)
              .FirstOrDefault();

if (book != null)
{
    int copies = (int) book.Element("NumberOfCopies");
}

当然,这假设您对于给定的书只有一个元素。

【讨论】:

  • .Element(name) 上的简单演员阵容是否有效?你不需要实际解析它吗?
  • @J.Steen:是的,它会起作用的。 XElement 有显式转换。
  • 甜蜜。这些课程还没有做很多。很高兴知道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
  • 2021-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多