Sean P
Sean P

Reputation: 949

Reading XML from document with VB.net

I want to be able to read my XML document but I am a little lost how to. I cant really post my XML on here because it is just trying to use markup. Anyways, I have a root node that surrounds the whole object i want to read. From there, there are a few elements. 2 of those elements can have multiple instances. There will only be one object i need to read from the XML document.

Thanks in advance. I hope I can explain enough without being able to post my XML

:::

Here is the code i have so far:

Private Function ExtractXMLFromFileToBonder(ByVal path As String) As Bonder
    Dim extractedBonder As New Bonder
    Dim settings As New XmlReaderSettings
    settings.IgnoreWhitespace = True

    settings.CloseInput = True

    Using reader As XmlReader = XmlReader.Create(path, settings)

        With reader

            .ReadStartElement("Machine_Name")
            MsgBox(.GetAttribute("Name"))

        End With

    End Using

    Return Nothing

End Function

Upvotes: 1

Views: 3576

Answers (4)

Kangkan
Kangkan

Reputation: 15571

Do something like

Dim m_xmld As XmlDocument
Dim m_nodelist As XmlNodeList
Dim m_node As XmlNode

'Create the XML Document
m_xmld = New XmlDocument()

'Load the Xml file
m_xmld.Load("YourPath\test.xml")

'Show all data in your xml
MessageBox.Show(m_xmld.OuterXml)


'Get the list of name nodes
m_nodelist = m_xmld.SelectNodes("/family/name")

'Loop through the nodes
For Each m_node In m_nodelist
'Get the Gender Attribute Value
Dim genderAttribute = m_node.Attributes.GetNamedItem("gender").Value

'Get the firstName Element Value
Dim firstNameValue = m_node.ChildNodes.Item(0).InnerText

'Get the lastName Element Value
Dim lastNameValue = m_node.ChildNodes.Item(1).InnerText

'Write Result to the Console
Console.Write("Gender: " & genderAttribute _
& " FirstName: " & firstNameValue & " LastName: " _
& lastNameValue)
Console.Write(vbCrLf)
Next

Upvotes: 1

Aim Kai
Aim Kai

Reputation: 2919

You could also use linq to xml.

Tutorials:

http://www.devcurry.com/2009/05/linq-to-xml-tutorials-that-make-sense.html

or

http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx

or I recommend this book Linq in Action published by manning..

http://linqinaction.net/

Upvotes: 1

Rune
Rune

Reputation: 8380

Check out System.Xml.XmlDocument and XPath.

Upvotes: 1

Kangkan
Kangkan

Reputation: 15571

Use the xml reader from System.xml to achieve this. You can use xmlreader of your choice. Refer the XML namespace at http://msdn.microsoft.com/en-us/library/system.xml%28VS.71%29.aspx

Upvotes: 1

Related Questions