2016-12-15 126 views
0

我想使用XPath選擇XML文檔的節點。但是,當XML文檔包含xml命名空間時它不起作用。 如何在考慮名稱空間的情況下使用XPath搜索節點?當XML文檔包含名稱空間時,選擇包含XPath的節點

這是我的XML文檔(簡體):

<ComponentSettings xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Company.Product.Components.Model"> 
    <Created xmlns="http://schemas.datacontract.org/2004/07/Company.Configuration">2016-12-14T10:29:28.5614696+01:00</Created> 
    <LastLoaded i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/Company.Configuration" /> 
    <LastSaved xmlns="http://schemas.datacontract.org/2004/07/Company.Configuration">2016-12-14T16:31:37.876987+01:00</LastSaved> 
    <RemoteTracer> 
    <TraceListener> 
     <Key>f987d7bb-9dea-49b4-a689-88c4452d98e3</Key> 
     <Url>http://192.168.56.1:9343/</Url> 
    </TraceListener> 
    </RemoteTracer> 
</ComponentSettings> 

我希望得到一個RemoteTracer標籤的標籤TraceListener的所有URL標記。 這是我如何得到他們,但這只是工作,如果XML文檔不使用命名空間:

componentConfigXmlDocument = new XmlDocument(); 
componentConfigXmlDocument.LoadXml(myXmlDocumentCode); 
var remoteTracers = componentConfigXmlDocument.SelectNodes("//RemoteTracer/TraceListener/Url"); 

目前,我的解決方法是刪除使用正則表達式從XML原始字符串的所有命名空間,裝載前XML。然後我的SelectNodes()工作正常。但那不是合適的解決方案。

+0

[在C#中使用XPath使用默認命名空間]的可能的複製(HTTP://計算器.com/questions/585812/using-xpath-with-default-namespace-in-c-sharp) –

+0

在StackOverflow上有1000個關於這個問題的答案。 –

回答

1

這裏有兩個命名空間。首先是

http://schemas.datacontract.org/2004/07/Company.Product.Components.Model 

根元素(ComponentSettingsRemoteTracer,一切都在它下面屬於這個名稱空間。第二個命名空間是

http://schemas.datacontract.org/2004/07/Company.Configuration 

CreatedLastLoadedSaved屬於它。

要獲得您需要的節點,您必須在xpath查詢中的所有元素前加上各自的名稱空間前綴。那些前綴的實際命名空間的映射,你可以這樣做:

var componentConfigXmlDocument = new XmlDocument();    
componentConfigXmlDocument.LoadXml(File.ReadAllText(@"G:\tmp\xml.txt")); 
var ns = new XmlNamespaceManager(componentConfigXmlDocument.NameTable); 
ns.AddNamespace("model", "http://schemas.datacontract.org/2004/07/Company.Product.Components.Model"); 
ns.AddNamespace("config", "http://schemas.datacontract.org/2004/07/Company.Configuration"); 

,然後查詢是這樣的:

var remoteTracers = componentConfigXmlDocument.SelectNodes("//model:RemoteTracer/model:TraceListener/model:Url", ns); 
+0

謝謝你的工作。我嘗試了很多,並搜索了符合我的起始情況的例子,但我沒有找到答案。但是,這工作。謝謝! – rittergig

相關問題