2012-09-25 87 views
0

我有一個XML文檔,我試圖讀取但我的查詢不返回任何結果。 使用查詢IM是...查詢xml文檔的節點--Visual Basic

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> 
+1

這份XML文檔不正確的結構。你有一個開放的標籤和兩個關閉的標籤。 –

+0

這只是因爲我的編輯不好(原來是1000s線長,所以我把它縮短了大部分,現在編輯出來 – ljsg

回答

1

試試這個:

Dim ns = doc.Root.GetDefaultNamespace() 

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

工作,謝謝肖恩 任何想法爲什麼原始方法不起作用 – ljsg

+0

因爲'DeviceInstance ''''''''''''''''''是命名空間限定的,你必須明確地指定命名空間 –

1

幾乎等同於@Sean明亮的答案(除略少將軍):

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

... 

Dim products = doc...<DeviceInstance>.Select(_ 
        Function(product) [email protected]) 

的LINQ唯一的解決辦法也是可能的(有效地將我的解決方案與Sean's結合起來):

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

... 

Dim products = From product In doc...<DeviceInstance> _ 
        Select [email protected] 

(這是未經測試)。

+0

yip,這也是可行的 我更喜歡Seans代碼,只是因爲我不太確定函數(產品)位是如何工作的。 – ljsg