如果“key”= PublicAddresses [PRIMARY] [0],我正在尝试检索属性“value”。我是新手,我正在努力学习VB.Net。
这是我的xml文档布局
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd">
<preferences EXTERNAL_XML_VERSION="1.0">
<root type="system">
<map/>
<node name="Level1">
<map/>
<node name="current">
<map/>
<node name="PublicIdentity">
<map>
<entry key="PublicAddresses[PRIMARY][0]" value="192.168.1.1"/>
<entry key="PublicAddresses[SECONDARY][0]" value="192.168.1.2"/>
</map>
</node>
</node>
</node>
</root>
</preferences>
这是我想出的,非常像意大利面条:
Imports System
Imports System.Xml
Module Module1
Sub Main()
Dim XmlDoc As XmlDocument = New XmlDocument
XmlDoc.Load("prefs.xml")
For Each Element As XmlElement In XmlDoc.SelectNodes("//*")
For Each Attribute As XmlAttribute In Element.Attributes
If Attribute.Name = "value" Then
Console.WriteLine("{0}", Attribute.Value)
End If
Next
Next
End Sub
结束模块
答案 0 :(得分:0)
使用谷歌搜索StackOverflow我能够找到这个宝石:
这是我的解决方案:
Sub Main()
Dim doc As XElement = XElement.Load("prefs.xml")
Dim primaryKey = "PublicAddresses[PRIMARY][0]"
Dim secondaryKey = "PublicAddresses[SECONDARY][0]"
Dim priResult = doc.Descendants("entry").Where(Function(user) CType(user.Attribute("key"), String) = primaryKey).SingleOrDefault
Dim secResult = doc.Descendants("entry").Where(Function(user) CType(user.Attribute("key"), String) = secondaryKey).SingleOrDefault
If priResult IsNot Nothing Then
Dim primaryIPAddress = CType(priResult.Attribute("value"), String)
Console.WriteLine(primaryIPAddress)
End If
If secResult IsNot Nothing Then
Dim secondaryIPAddress = CType(secResult.Attribute("value"), String)
Console.WriteLine(secondaryIPAddress)
End If
End Sub