c# 使用一种方法按元素或属性排序

c# sort by elements or attribute with one method

我需要对 xml 文档进行排序,有时按属性排序,有时按元素排序,具体取决于文档的类型。如何使用 c# 中的一种 sortBy 方法解决此问题?非常感谢您的帮助!例如我的排序键是 "bookID" 元素或属性,xml 文件是:

 <bookstore>
  <book>
    <bookID>100</bookID>
    <name> The cat in the hat <name>
  </book>
  <book>
    <bookID>90</bookID>
    <name> another book <name>
  </book>
  <book>
    <bookID>103</bookID>
    <name> a new book <name>
  </book>
  </bookstore>

或者有时 xml 的格式如下:

<bookstore>
  <book bookID="100">The cat in the hat</book> 
  <book bookID="90">another book</book> 
  <book bookID="103"> a new book</book> 
</bookstore>

假设您为此使用 Linq-to-XML,您将需要在查询中处理这两种可能性。您可以使用 let 关键字,但基本思想是检查属性或元素是否为 null 并使用适当的值。

var books = from book in document.Element("bookstore").Elements("book")
            let bookId = book.Attribute("bookID") != null 
                ? book.Attribute("bookID").Value 
                : book.Element("bookID").Value
            orderby int.Parse(bookId)
            select book; // project properties of book as needed