Reputation: 9610
I need to enumerate an XML (XDocument) document as such...
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<applied>
<ah ID="8298" userId="87459" roleId="2700" />
<ah ID="8300" userId="87459" roleId="2699" />
<ah ID="8299" userId="87460" roleId="2700" />
</applied>
...and extract all the values of userID
and roleID
into two separate StringBuilder
objects.
I've been messing about with Linq for the first time, but am struggling, and would appreciate some help please (this is a VB webforms app). I have seen lots of Linq example that get a single value, but not two at the same time in the manner I need.
Also, this XML file could be up to 100,000 rows in length. Is Linq more memory efficient than, say, a FOR EACH
loop? If not, could someone please provide a FOR EACH
example?
Thanks in advance.
Update: The result would be:
Userids = "87459,87459,87460"
roleIds = "2700,2699,2700"
Upvotes: 0
Views: 326
Reputation: 15774
First, you need to get the xml from your file system into memory. This is called deserialization. My preferred method of doing this is using a model for the xml, which is just a class with some attributes to tell the xml serializer how to parse the file:
<XmlRoot("applied")> _
Public Class Applied
<XmlElement("ah")> _
Public Property AhList As List(Of Ah)
End Class
Public Class Ah
<XmlAttribute("ID")> _
Public Property ID As Integer
<XmlAttribute("userID")> _
Public Property UserID As Integer
<XmlAttribute("roleID")> _
Public Property RoleID As Integer
End Class
Note that the XmlAttribute tells the serializer exactly what the attribute is called in xml, but you may use any name for it in the model, i.e. <XmlAttribute("userID")> Public Property UserID As Integer
.
Now that you have this model, you need to deserialize from xml.
Dim appls As New Applied()
Dim serializer As XmlSerializer = Nothing
serializer = New XmlSerializer(GetType(Applied))
appl = serializer.Deserialize(xd.CreateReader()) ' xd is your XDocument
Now you should have all the xml deserialized into the appls
object. This object has a property, according to the model, called AhList
, which is a list of all the elements in your xml. Since List(Of Ah) is IEnumerable, you can use LINQ on it.
Upvotes: 1