C#使用一种方法按元素或属性排序 [英] c# sort by elements or attribute with one method

查看:358
本文介绍了C#使用一种方法按元素或属性排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to sort xml documents sometimes by attributes, sometimes by elements, depending on what type of documents comes in. How can I use one sortBy method in c# to solove this problem? Many thanks for your help! For example my sorting key is "bookID"element or attribute, and the xml files are:

 <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并使用适当的值.

You will need to handle both possibilities in your query, assuming your using Linq-to-XML for this. You might utilize the let keyword, but the basic idea is to check for either the attribute or the element for null and use the appropriate value.

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

这篇关于C#使用一种方法按元素或属性排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆