如何在VB.NET中读取XML元素

时间:2012-07-20 14:48:51

标签: xml vb.net

我有一个非常简单的问题,但由于我是XML的新手,我遇到了一些问题。我有这个XML文档:

<?xml version="1.0" encoding="utf-8"?>  
<Form_Layout>
  <Location>
    <LocX>100</LocX>
    <LocY>100</LocY>  
  </Location>  
  <Size>  
    <Width>300</Width>  
    <Height>300</Height>  
  </Size>  
</Form_Layout> 

我想要做的是将LocX,LoxY,Width和Height元素中的值读入相应的变量。

以下是我的尝试:

Dim XmlReader = New XmlNodeReader(xmlDoc)  
While XmlReader.Read  
    Select Case XmlReader.Name.ToString()  
        Case "Location"  
            If XmlReader.??  
        Case "Size"  
            If XmlReader.??
    End Select  
End While  

但是,我无法弄清楚如何访问每个子节点。

3 个答案:

答案 0 :(得分:3)

如果您能够使用Linq to XML,则可以使用VB的XML Axis Properties

Dim root As XElement = XDocument.Load(fileName).Root

Dim LocX = Integer.Parse(root.<Location>.<LocX>.Value)
Dim LocY = Integer.Parse(root.<Location>.<LocY>.Value)

root.<Location>.<LocY>.Value = CStr(120)也有效。

答案 1 :(得分:0)

以下是使用XmlDocument和XPath执行此操作的方法。我相信其他人会很乐意使用XDocument和LINQ。

自愿提供示例
Dim doc As New XmlDocument()
doc.LoadXml("...")
Dim locX As Integer = Integer.Parse(doc.SelectSingleNode("/FormLayout/Location/LocX").InnerText)
Dim locY As Integer = Integer.Parse(doc.SelectSingleNode("/FormLayout/Location/LocY").InnerText)
Dim width As Integer = Integer.Parse(doc.SelectSingleNode("/FormLayout/Size/Width").InnerText)
Dim height As Integer = Integer.Parse(doc.SelectSingleNode("/FormLayout/Size/Height").InnerText)

另外,您可能需要查看XmlSerializer类,看看您是否感兴趣。该类将读取XML文档并使用它来填充新的属性值宾语。您只需要创建一个模仿XML结构的类,以便反序列化为。

答案 2 :(得分:0)

使用LINQ-XML,

Dim root As XElement = XDocument.Load(fileName).Root

Dim LocX = Integer.Parse(root.Element("Location").Element("LocX").Value)
Dim LocY = Integer.Parse(root.Element("Location").Element("LocY").Value)
相关问题