1

I have code for reading XML elements like this:

Dim xmlRoot As XElement = XDocument.Load("x:\books.xml").Root

For Each book As XElement In xmlRoot.<book>
     Debug.WriteLine(book.<title>.Value)
     Debug.WriteLine(book.<author>.Value)
     Debug.WriteLine(book.<year>.Value)
     Debug.WriteLine(book.<price>.Value)
Next

What I want now is, how to display only 10 elements. Now I have displayed all xml elements but I need only first 10. Tried with few For loop combinations but didn't get it work.

Thanks

1
  • what combinations have you tried? Commented Nov 23, 2014 at 0:02

2 Answers 2

3

Like this - notice Take(10) at the end:

For Each book As XElement In xmlRoot.<book>.Take(10)

Take is an extension method on IEnumerable, you can use it with anything, not just XElements.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank You! Didn't know about the "Take" extension. Thanks again.
1

You could add your own indicator to your existing For.

Dim i As Integer = 0 'No loops yet
For Each book As XElement In xmlRoot.<book>
    Debug.WriteLine(book.<title>.Value)
    Debug.WriteLine(book.<author>.Value)
    Debug.WriteLine(book.<year>.Value)
    Debug.WriteLine(book.<price>.Value)

    i = i + 1 'Completed one more loop
    If (i = 10) Then Exit For 'Completed 10 loops, so stop
Next

Comments

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.