查询xml文档的节点 - Visual Basic

时间:2012-09-25 12:36:45

标签: xml vb.net

我有一个XML文档,我试图阅读,但我的查询不会返回没有结果。  使用的查询是...

Dim products = From product In doc.Descendants("DeviceInstance") _
    Select product.Attribute("ProductRefId").Value

For Each result In products
    MessageBox.Show(result.ToString())
Next

我哪里错了?

见下面的xml

<?xml version="1.0"?>
<KNX xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://knx.org/xml/project/10" CreatedBy="knxconv" ToolVersion="4.0.1004.62808">
  <Project Id="P-0225">
    <Installations>
      <Installation Name="" InstallationId="0">
        <Topology>
          <Area Id="P-0225-0_A-734" Name="East" Address="1" Description="">
            <Line Id="P-0225-0_L-736" Name="Ground" Address="1" MediumTypeRefId="MT-0" Comment="" Description="">
              <DeviceInstance Name="" Id="P-0225-0_DI-761" ProductRefId="M-0064_H-MTN647893-1-O000C_P-MTN647893" Hardware2ProgramRefId="M-0064_H-MTN647893-1-O000C_HP-480B-21-4CB2-O000C" Address="5" Comment="" LastModified="2012-07-04T19:27:44" LastDownload="2012-08-22T11:27:40" InstallationHints="" IndividualAddressLoaded="true" ApplicationProgramLoaded="true" ParametersLoaded="true" CommunicationPartLoaded="true" MediumConfigLoaded="true" Description="SWA1101" IsCommunicationObjectVisibilityCalculated="true">
                <ParameterInstanceRefs>
                  <ParameterInstanceRef RefId="M-0064_A-480B-21-4CB2-O000C_P-1_R-1" Value="0"/>
                  <ParameterInstanceRef RefId="M-0064_A-480B-21-4CB2-O000C_P-2834_R-2834" Value="0"/>
                  <ParameterInstanceRef RefId="M-0064_A-480B-21-4CB2-O000C_P-2835_R-2835" Value="0"/>
                </ParameterInstanceRefs>
                <ComObjectInstanceRefs>
                  <ComObjectInstanceRef RefId="M-0064_A-480B-21-4CB2-O000C_O-31_R-243" IsActive="true">
                  </ComObjectInstanceRef>
                  <Connectors>
                    <Send GroupAddressRefId="P-0225-0_GA-128"/>
                  </Connectors>
                </ComObjectInstanceRefs>
              </DeviceInstance>
            </Line>
          </Area>
        </Topology>
      </Installation>
    </Installations>
  </Project>
</KNX>

2 个答案:

答案 0 :(得分:1)

试试这个:

Dim ns = doc.Root.GetDefaultNamespace()

Dim products = From product In doc.Descendants(ns + "DeviceInstance") _
    Select product.Attribute("ProductRefId").Value

答案 1 :(得分:1)

几乎相当于@Sean Bright的答案(除了稍微不那么一般):

Imports <xmlns="http://knx.org/xml/project/10">

...

Dim products = doc...<DeviceInstance>.Select( _
                   Function(product) product.@ProductRefId)

LINQ唯一解决方案也是可行的(有效地将我的解决方案与Sean合并):

Imports <xmlns="http://knx.org/xml/project/10">

...

Dim products = From product In doc...<DeviceInstance> _
                   Select product.@ProductRefId

(这是未经测试的。)