2013-03-15 221 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