預期我有以下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.
所有建議和幫助很好地收到。
感謝
本
您的文檔混合了不同的命名空間。您的查詢不使用名稱空間。 – 2015-02-10 19:23:10
假設你修復命名空間問題,看起來你很好。你的心是否設置在XPath上?使用XDocument來執行LINQ to XML查詢我發現使用起來更容易(雖然如果XML文檔非常大並且需要緩衝但不好用) – JNYRanger 2015-02-10 19:24:34
@JNYRanger嗨,使用XPath的原因就是我之前已經使用過它,但從來沒有使用過命名空間,因此也存在這個問題。如果我使用LINQ to XML輕鬆修改XML文檔,我可以嗎?因爲這只是我將添加更多數據的基本模板。對於那些有興趣提交給英國稅務和海關的人。 – 2015-02-10 19:43:41