views:

91

answers:

1
+1  Q: 

Linq Comment VB

How do you retrieve a comment from an XMLElement using Linq in VB? For example:

<MyXML>
  <event type="MyEvent" uid="3">
    <start>2009-02-01T12:00:00</start>
    <stop>2009-02-01T12:00:30</stop>
    <New>1</New>
    <x>20</x>
    <y>60</y>
    <!--Whatever-->
  </event>
  <event type="MyEvent" uid="3">
    <start>2009-02-01T11:00:00</start>
    <stop>2009-02-01T11:00:30</stop>
    <New>3</New>
    <x>21</x>
    <y>67</y>
    <!--Second Whatever-->
  </event>
</MyXML>

If I wanted to loop through the events and retrieve the comments.

+2  A: 

Do you mean XmlElement, or XElement? With XElement you could just use

element.DescendantNodes().OfType(Of XComment)()

(I hope that's the right syntax for generics - in C# it would be OfType<XComment>().)

Jon Skeet
Does not appear to work. Using XML above and this code Dim doc As XDocument Dim element As XElement Dim item As XComment doc = XDocument.Load("C:\Junk\MyXML.xml") For Each element In doc.Root.Elements For Each item In element.Descendants().OfType(Of XComment)() Debug.Print("here") Debug.Print(item.Value.ToString) Next NextIt never reaches Here. It is like the comments are not loaded in.
AudioDan
Shoot - I do not seem to have rep enough to edit my comment, and it knocked out the code formatting in this comment. But the suggestion does not appear to work unless I am missing something.
AudioDan
Never mind - your answer is basically correct. I was using descendants and not descendant Nodes. This works For Each item In element.DescendantNodes().OfType(Of XComment)()
AudioDan
Thanks, have edited answer to remove the extraneous Get.
Jon Skeet
Just a note: comments are not editable. You can delete it and repost it with the changes needed
Eduardo Molteni