当XML文档包含名称空间时,选择包含XPath的节点

问题描述:

我想使用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

在*上有1000个关于这个问题的答案。 –

这里有两个命名空间。首先是

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