1

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>

or sometimes the xml comes in the below format:

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

1 Answer 1

1

You will need to handle both possibilities in your query, assuming you are 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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply! somehow bookId = book.Attribute("bookID") != null soes not work for me. It always returns true whether there is attribute or not..
Is "bookID" of a differing case in your actual XML? I took both your XML snippets (and had to clean one up, your "name" elements are not properly closed) and the code executed successfully on each.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.