从xml doc元素中检索单个属性值

时间:2013-03-15 12:13:37

标签: xml vb.net

我有一个带有以下结构的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>

我正在尝试填充大陆名称的下拉列表,通过访问name属性并填充列表以绑定到下拉列表,仅检索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

1 个答案:

答案 0 :(得分:4)

这是一所古老的学校,但它的工作原理非常易读/可维护......

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