使用xml直接访问xml属性值

时间:2014-04-01 23:05:29

标签: .net xml vb.net

我的xml如下:

<Team>
<Member Name="Alex" Info="&lt;Details Weight=&quot;80&quot; Category=&quot;Fighter&quot; LastFight=&quot;2014-03-01&quot; /&gt;"/>
</Team>

我想找到一种方法来直接加载Attribute LastFight而不会创建大量的xmldocuments。这是我使用的代码:

Dim storagexml As New XmlDocument
storagexml.LoadXml(<Team><Member Name="Alex" Info="&lt;Details Weight=&quot;80&quot; Category=&quot;Fighter&quot; LastFight=&quot;2014-03-01&quot; /&gt;"/></Team>)
Dim tempnodelist As XmlNodeList = storagexml.SelectNodes("Team/Member")
For Each tempnode As XmlNode In tempnodelist
If tempnode.Attributes("Name") IsNot Nothing Then
Dim tempdoc As New XmlDocument
tempdoc.LoadXml(tempnode.Attributes("Info").Value)
Dim tempsel As XmlNode = tempdoc.SelectSingleNode("Info")
If Not tempsel.Attributes("LastFight").Value.Trim() = "" Then
RichTextBox1.AppendText(tempnode.Attributes("Name").Value & " " & tempsel.Attributes("LastFight").Value & vbCrLf)
End If

1 个答案:

答案 0 :(得分:0)

Info属性的值是另一个XML字符串,因此,据我所知,您无法将其加载到另一个XML抽象对象(f.e XmlDocument)。

无论如何,您可以使用LINQ-to-XML简化代码。例如,使用XElement和VB.NET特定功能来访问XML内联部分:

Dim xml = <Team>
              <Member Name="Alex" Info="&lt;Details Weight=&quot;80&quot; Category=&quot;Fighter&quot; LastFight=&quot;2014-03-01&quot; /&gt;"/>
          </Team>

'notice how to access child element and attribute inline :
'
Dim info = XElement.Parse(xml.<Member>.@Info)
Dim lastFight As String = info.@LastFight
Console.WriteLine(lastFight)