使用VB.net从文档中读取XML

时间:2010-02-22 16:23:06

标签: xml vb.net

我希望能够阅读我的XML文档,但我有点迷失方向。我不能在这里发布我的XML,因为它只是试图使用标记。无论如何,我有一个根节点,围绕我想要阅读的整个对象。从那里,有一些元素。其中2个元素可以有多个实例。我只需要从XML文档中读取一个对象。

提前致谢。我希望我能解释得足够,而不能发布我的XML

:::

这是我到目前为止的代码:

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

4 个答案:

答案 0 :(得分:1)

使用System.xml中的xml阅读器来实现此目的。您可以使用您选择的xmlreader。请参阅http://msdn.microsoft.com/en-us/library/system.xml%28VS.71%29.aspx

处的XML命名空间

答案 1 :(得分:1)

答案 2 :(得分:1)

你也可以使用linq到xml。

教程:

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

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

或者我推荐这本书由曼宁出版的Linq in Action。

http://linqinaction.net/

答案 3 :(得分:1)

执行类似

的操作
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
相关问题