How can I find the sibling of an XML Element with Visual Basic? Let’s say I have:
<Data>
<Mail>
<Subject>Welcome!</Subject>
<From>Antonios</From>
<Content>Welcome! How can I assist you?</Content>
</Mail>
<Mail>
<Subject>Test!</Subject>
<From>John</From>
<Content>Hello Friend!</Content>
</Mail>
</Data>
Now I have a list box that adds every Subject, so the list shows: Welcome! and Test!
Now I want that, when I click on “Welcome!”, a Text Box shows the content of the “From” element of “Welcome!” and another Text Box shows the “Content” element of “Welcome”.
In other words, I’m looking for the Sibling of a specific element.
You can do this in multiple ways. Here is how you can do it using
XmlDocumentand XPath:Obviously, since the subject may not be unique, it would be better to use some element that is a unique ID, or you could do it by index. For instance, this selects from the first mail message:
However, the best way to do something like this is to load all of the required data into memory up-front. Unless the amount of data is too great, which it doesn’t sound like it is, that usually makes the most sense. So, for instance, I would recommend creating a data object that represents a mail message, for instance:
Then, you can load one
Mailobject for each Mail element in the XML. Because theToStringmethod is overriden to display the subject, you can just add the objects directly to the list box, for instance:Then, when an item in the list box is selected, you can cast the selected item to the
Mailtype and access its properties, for instance:However, at that point, if the data is not too large, it’s even easier to just use the
XmlSerializerto simply deserialize the XML into an object, for instance, start by creating a class that defines the entire XML document, like this:Then load the XML into the list box like this (where
xmlis a string containing the XML document):Or, if you want to read from an XML file directly instead of deserializing it from a string:
To answer your second question that you asked in your comment below, to delete a given mail message, you could do it like this: