2015-02-10 36 views
1

預期我有以下XML文檔無法使用XPath的文檔

<?xml version="1.0" encoding="utf-8"?> 
<GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope"> 
    <EnvelopeVersion>2.0</EnvelopeVersion> 
    <Header> 
    <MessageDetails> 
     <Class> 
     </Class> 
     <Qualifier>request</Qualifier> 
     <Function>submit</Function> 
     <CorrelationID /> 
     <Transformation> 
     </Transformation> 
     <GatewayTest>0</GatewayTest> 
    </MessageDetails> 
    <SenderDetails> 
     <IDAuthentication> 
     <SenderID> 
     </SenderID> 
     <Authentication> 
      <Method>clear</Method> 
      <Role>principal</Role> 
      <Value></Value> 
     </Authentication> 
     </IDAuthentication> 
    </SenderDetails> 
    </Header> 
    <GovTalkDetails> 
    <Keys> 
     <Key Type="TaxOfficeNumber"> 
     </Key> 
     <Key Type="TaxOfficeReference"> 
     </Key> 
    </Keys> 
    <TargetDetails> 
     <Organisation>IR</Organisation> 
    </TargetDetails> 
    <ChannelRouting> 
     <Channel> 
     <URI> 
     </URI> 
     <Product></Product> 
     <Version> 
     </Version> 
     </Channel> 
     <timestamp> 
     </timestamp> 
    </ChannelRouting> 
    </GovTalkDetails> 
    <Body> 
    <IRenvelope xmlns=""> 
     <IRheader> 
     <Keys> 
      <Key Type="TaxOfficeNumber"> 
      </Key> 
      <Key Type="TaxOfficeReference"> 
      </Key> 
     </Keys> 
     <PeriodEnd> 
     </PeriodEnd> 
     <DefaultCurrency>GBP</DefaultCurrency> 
     <IRmark> 
     </IRmark> 
     <Sender>Employer</Sender> 
     </IRheader> 
    </IRenvelope> 
    </Body> 
</GovTalkMessage> 

,我使用XMLDocument.load()加載到一個XMLDocument

現在,當我對它運行xpath查詢時,它們沒有按照我的預期做出響應,而且我也無法找到原因,我使用了XPath Visualiser工具,它顯示了例如// Keys/Key應該返回4個節點

當我運行下面的C#

document.SelectNodes(@"//Keys/Key") it returns 2 nodes not the expected 4. 

而且當我運行下面的

document.SelectNodes(@"//Header") it returns 0 nodes 

還運行

document.SelectNodes(@"GovTalkMessage") returns 0 nodes. 

所有建議和幫助很好地收到。

感謝

+1

您的文檔混合了不同的命名空間。您的查詢不使用名稱空間。 – 2015-02-10 19:23:10

+0

假設你修復命名空間問題,看起來你很好。你的心是否設置在XPath上?使用XDocument來執行LINQ to XML查詢我發現使用起來更容易(雖然如果XML文檔非常大並且需要緩衝但不好用) – JNYRanger 2015-02-10 19:24:34

+0

@JNYRanger嗨,使用XPath的原因就是我之前已經使用過它,但從來沒有使用過命名空間,因此也存在這個問題。如果我使用LINQ to XML輕鬆修改XML文檔,我可以嗎?因爲這只是我將添加更多數據的基本模板。對於那些有興趣提交給英國稅務和海關的人。 – 2015-02-10 19:43:41

回答

0

的XPath需要命名空間。您嘗試選擇的標籤位於同一個標籤中,因此您必須告訴選擇的位置。

+0

嗨,這已經解決了我所遇到的問題,因爲文檔將有兩個名稱空間,無論如何在兩個名稱空間中選擇比使用本地名稱更好。 ? 在一些xpath中,我可能希望所有匹配的節點,而不管命名空間。 – 2015-02-10 19:40:05

+0

對於這個特定的問題並不是一個令人滿意的答案。您應該擴展此評論,並且實際上_explain_如何考慮名稱空間。 @BenWhyall如果一個元素'a'應該與其名稱空間無關,則必須使用'// *:a'或'// * [local-name()='a']''。 – 2015-02-10 20:03:24

+0

@MathiasMüller感謝這些信息,我將能夠解決我的問題 – 2015-02-11 22:40:16