【问题标题】:Retrieve XML attribute value based on previous attribute value VB.Net根据先前的属性值 VB.Net 检索 XML 属性值
【发布时间】:2016-06-17 05:59:43
【问题描述】:

如果“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

结束模块

【问题讨论】:

    标签: xml vb.net


    【解决方案1】:

    使用谷歌搜索 StackOverflow 我能够找到这个 gem:

    Solution

    这是我的解决方案:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多