1

我有一个 VB.net 程序。我正在尝试使用 XMLReader 读取 .xml 文件。我想分解 XML 文件以将其组织成不同的“部分”在这个例子中"FormTitle""ButtonTitle". 我想从中获取<Text>数据FormTitle并将其显示为表单"text",然后将其显示<Text>"ButtonTitle"按钮文本中。

这是我的 XML 文件:

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

这是我当前的代码:

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

    Dim document As XmlReader = New XmlTextReader("C:\testing.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

怎么能带入下一段(ButtonTitle)同名即在FormTitle哪是(Text)。我会假设我需要在 if then 语句中引用FormTitle和?ButtonTitle

4

2 回答 2

2

看看这个例子。http://msdn.microsoft.com/en-us/library/dc0c9ekk.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2

你应该可以使用:

doc.GetElementsByTagName("FormTitle")

然后,您可以遍历所有子节点。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 
于 2013-04-10T18:34:46.813 回答
1

使用 XDocument 更有效地读取 Xml,并且由于语法更少,可读性也更高。

您需要将根添加到您的 XML。我称它为根,但它可以是任何东西。它只是封装了你所有的 XML

<?xml version="1.0" encoding="utf-8"?>
<root>
<FormTitle>
    <Text>Form Test</Text>
</FormTitle>
<ButtonTitle>
    <Text>Button Test</Text>
</ButtonTitle>
</root>

这是从 FormTitle 中提取“表单测试”的示例

    Dim document As XDocument = XDocument.Load("c:\tmp\test.xml")
    Dim title = From t In document.Descendants("FormTitle") Select t.Value

将文本分配给表单

Form1.Text = title.First()
于 2013-04-10T18:47:07.587 回答