Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
829 views
in Technique[技术] by (71.8m points)

vb.net - How to read an XML File

I have a VB.net program. I'm attempting to use XMLReader to read a .xml file. I want to break the XML File up to organize it into different "Sections" In this example "FormTitle" and "ButtonTitle". I would like to grab the <Text> data from FormTitle and display it as the Form "text" and take the <Text> in "ButtonTitle" and have it display in the button text.

Here is my XML File:

<?xml version="1.0" encoding="utf-8"?>
<!--XML Database.-->
<FormTitle>
    <Text>Form Test</Text>
</FormTitle>
<ButtonTitle>
    <Text>Button Test</Text>
</ButtonTitle>

Here is my current Code:

If (IO.File.Exists("C:esting.xml")) Then

    Dim document As XmlReader = New XmlTextReader("C:esting.xml")

    While (document.Read())

        Dim type = document.NodeType


        If (type = XmlNodeType.Element) Then

            '
            If (document.Name = "Text") Then
                Me.Text = document.ReadInnerXml.ToString()


            End If



        End If


    End While

Else

    MessageBox.Show("The filename you selected was not found.")
End If

How can bring in the next section (ButtonTitle) With the same name that is in FormTitle which is (Text). I would assume I need to reference FormTitle and ButtonTitle in an if then statement?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Check out this example. http://msdn.microsoft.com/en-us/library/dc0c9ekk.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2

You should can use:

doc.GetElementsByTagName("FormTitle")

You can then loop through all of the child nodes. http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.childnodes.aspx

    Dim root As XmlNode = doc.GetElementsByTagName("FormTitle").Item(1)

    'Display the contents of the child nodes. 
    If root.HasChildNodes Then 
        Dim i As Integer 
        For i = 0 To root.ChildNodes.Count - 1
            Console.WriteLine(root.ChildNodes(i).InnerText)
        Next i
    End If 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...