Link to home
Start Free TrialLog in
Avatar of Stacey Fontenot
Stacey Fontenot

asked on

Capture Element Attributes in XML using VB.Net

I need a way of looping through an XML document and obtaining values using VB.net for the following: PHYSICALADDRESS:Street; PHYSICALADDRESS:city; PHYSICALADDRESS:state;TAXID:SSN;DOB:dob. I would like these values in seperate string variable so I can use later. See the attached XML document.
EX_sample_XML.txt
ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Stacey;

Here is a code snippet that should meet your needs.
'' Load the XML file
Dim xdoc = XDocument.Load("Path and file name here")
'' XML Namespace needed to access the nodes
Dim at As XNamespace = "urn:v556"
'' Query the information and create a class object with the fields populated
Dim results = (From n In xdoc.Root.Descendants(at + "INDIVIDUAL")
               Let address = n.Element(at + "CONTACTINFO").Element(at + "PHYSICALADDRESS") 
               Let street1 = address.Attribute("street1").Value.Trim
               Let street2 = address.Attribute("street2").Value.Trim
               Let city = address.Attribute("city").Value.Trim
               Let state = address.Attribute("state").Value.Trim
               Let idinfo = n.Element(at + "IDINFO")
               Let taxId = idinfo.Element(at + "TAXID").Attribute("ssn").Value.Trim
               Let dob = DateTime.Parse(idinfo.Element(at + "DOB").Attribute("dob").Value.Trim)
               Select New Individual() With
               {
                .TaxId = taxId,
                .Dob = dob,
                .Street1 = street1,
                .Street2 = street2,
                .City = city,
                .State = state
               }).ToList()

'' Access the data
For Each item In results
    Console.WriteLine("{0} : {1} : {2} : {3} : {4} : {5}", item.TaxId, item.Dob, item.Street1, item.Street2, item.City, item.State)
Next


'' Class used to return the results
Public Class Individual
    Public Property Street1 As String
    Public Property Street2 As String
    Public Property City As String
    Public Property State As String
    Public Property TaxId As String
    Public Property Dob As DateTime
End Class

Open in new window