.NET:使用 XPATH 读取有 xmlns 属性的 XML 文档出现的问题

问题

xml

1 <sqlMap namespace="WHTR.Dao.Accounts" xmlns="http://ibatis.apache.org/mapping"
2   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
3 
4 </sqlMap>

这种带有 xmlns 属性的文档如果使用正常的 xpath 语法是获取不到元素或属性的。

正确的代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.IO;
 7 using System.Xml;
 8 
 9 namespace CSharpStudy
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             var xmlDocument = new XmlDocument();
16             xmlDocument.Load(@"E:段光伟代码摇钱树PPmoney_NewLibrariesWHTR.DaoAccountsImplsSqlMapSuperviseAccount.xml");
17             var nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
18             nsmgr.AddNamespace("b", "http://ibatis.apache.org/mapping");
19             var nodes = xmlDocument.SelectNodes("//b:select", nsmgr);
20             foreach (XmlNode node in nodes)
21             {
22                 Console.WriteLine(node.Attributes["id"].Value.Split('.').Last());
23             }
24         }
25     }
26 }

参考网站

http://codeclimber.net.nz/archive/2008/01/09/How-to-query-a-XPath-doc-that-has-a-default.aspx

http://stackoverflow.com/questions/2075773/xpath-for-xml-with-namespace

原文地址:https://www.cnblogs.com/happyframework/p/3672400.html