2012-07-20 541 views
2

我有一個非常簡單的問題,但由於我是XML新手,我遇到了一些問題。我有這樣的XML文檔:如何在VB.NET中讀取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,氧基,寬度和高度元素的值到我相應的變量。

這是我曾嘗試:

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 

但是,我想不出如何訪問每個子節點。

+1

您正在使用哪個版本的.NET? – Inisheer 2012-07-20 14:53:40

回答

3

如果你能使用LINQ到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)工作過。

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的結構以反序列化的類。

+0

非常感謝。 如果有人可以舉一個例子用LINQ我會很高興 – Nianios 2012-07-20 15:20:11

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) 
+0

非常感謝你 – Nianios 2012-07-20 15:35:18

+0

另外一個問題是如果我想做相反的事情: root.Element(「Location」)。Element(「LocX」 ).Value = locX'locX是我的變量 是嗎? – Nianios 2012-07-20 15:40:11