2013-03-15 196 views
0

我有一個XML文檔結構如下從XML文檔元素

<?xml version="1.0" encoding="utf-8" ?> 
<CoordinateData> 
    <Continent name="Australia"> 
    <Country name="Australia"> 
    <Marker custid="1">  
     <LocationName>Port of Brisbane</LocationName> 
     <Longitude>153.1678</Longitude> 
     <Latitude>-27.3832</Latitude>  
    </Marker> 
    <Marker custid="1">  
     <LocationName>Port of Newcastle</LocationName> 
     <Longitude>151.7833</Longitude> 
     <Latitude>-32.9333</Latitude>  
    </Marker> 
    </Country> 
    </Continent> 
    <Continent name="North America"> 
    <Country name="Canada"> 
     <Marker custid="2">  
      <LocationName>Port of Toronto</LocationName> 
      <Longitude>79.3724</Longitude> 
      <Latitude>43.633</Latitude>  
     </Marker> 
     <Marker custid="2">  
      <LocationName>Port of Vancouver</LocationName> 
      <Longitude>122.422</Longitude> 
      <Latitude>45.386</Latitude>  
     </Marker> 
    </Country> 
    </Continent> 
</CoordinateData> 

我試圖填充大陸名稱的下拉列表檢索單個屬性值,僅檢索那些具有在XML文件中的元素通過訪問那裏名稱屬性和填充列表綁定到下拉列表。

我似乎可以得到正確的語法我不斷收到對象引用錯誤。 這是我最近的一次迭代,這也是行不通的。我正在通過「大陸」功能

Public Shared Function GetContinentList(ByVal nodestring As String) As List(Of String) 
    Dim doc As New XmlDocument() 

    doc.Load(Hosting.HostingEnvironment.MapPath(xmlfilepath_InjectLocation))  
    Dim list As List(Of String) = (From attribute As XmlAttribute In doc.DocumentElement(nodestring).Attributes() Select (attribute("name").Value)).ToList() 

    Return list 
End Function 

工作功能;

Public Shared Function GetContinents() As List(Of String) 
    Dim doc As New XmlDocument() 
    doc.Load(Hosting.HostingEnvironment.MapPath(XmlfilepathInjectLocation)) 
    Return (From node As XmlNode In doc.SelectNodes("//Continent/@name") Select node.InnerText).ToList() 

End Function 

現在我試圖訪問一次伊夫選擇一個大陸 國家屬性,這是我最新的嘗試,似乎都返回0項。需要

Public Shared Function GetContinentSubItems(ByVal continentname As String) As List(Of String) 
    Dim doc As New XmlDocument() 
    doc.Load(Hosting.HostingEnvironment.MapPath(XmlfilepathInjectLocation)) 
    Return (From node As XmlNode In doc.SelectNodes("///Country/@name") Where doc.SelectSingleNode("CoordinateData/Continent").Attributes("name").Value = continentname Select node.InnerText.ToList() 
End Function 

回答

3

這是一個年紀大一點的學校,但它的工作原理,是非常可讀/維護...

Public Function GetContinents() As List(Of String) 
    Dim doc As New XmlDocument 
    doc.Load("c:\yourfile.xml") 
    Dim ReturnValue As New List(Of String) 
    For Each node As XmlNode In doc.SelectNodes("//Continent") 
     ReturnValue.Add(node.Attributes("name").Value) 
    Next 
    Return ReturnValue 
End Function 
+0

一些細微的變化,但幫我弄明白 – dinotom 2013-03-15 13:26:44

+1

我同意。 XPath是完美的解決方案。更好的是,使用'doc.SelectNodes(「// Continent/@ name」)'來選擇實際的屬性值,然後在循環內用'ReturnValue.Add(node.InnerText)'將它們添加到列表中。 – 2013-03-15 13:27:34

+0

謝謝你們兩位,一旦選擇了大陸,我現在正在努力如何檢索非洲大陸下的國家。 – dinotom 2013-03-15 21:24:25