Which namespace is necessary to use SelectSingleNode() method (using default namespace and can't use the method)

此生再无相见时 提交于 2019-11-30 09:49:08

问题


Hi I have xml file (which is actually msbuild file) that uses different namespace

<?xml version="1.0" ?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup Condition="'$(key)'=='1111'">
          <Key>Value</Key>
    </PropertyGroup>
</Project>

But the problem is I can't use SelectSingleNode with that file because of

xmlns="http://schemas.microsoft.com/developer/msbuild/2003"

I believe it's since default namespace (necessary for the method) is gone because of xmlns above. Then I think I just need to add necessary one for that.. But my tries weren't successful at all. Could you please give me a quick example how to do this?

Here is how I did. (I also tried to added multiple namespaces but weren't successful..)

XmlDocument xml = new XmlDocument();
xml.Load("ref.props");        
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003");

XmlNode platform_node
  = xml.SelectSingleNode("//msbld:PropertyGroup[contains(@Condition, '1111')]", nsmgr);

回答1:


You need to use the correct namespace, which is "http://schemas.microsoft.com/developer/msbuild/2003".

Try

XmlDocument xml = new XmlDocument();
xml.Load("ref.props");        
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("ms", "http://schemas.microsoft.com/developer/msbuild/2003");

XmlNode platform_node
  = xml.SelectSingleNode("/ms:Project/ms:PropertyGroup[contains(@Condition, '1111')]",
                         nsmgr);

Don't confuse the namespace prefix (which was empty in the XML) with the namespace, which is "http://schemas.microsoft.com/developer/msbuild/2003".



来源:https://stackoverflow.com/questions/14698271/which-namespace-is-necessary-to-use-selectsinglenode-method-using-default-nam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!