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

本文介绍如何处理XML文档中包含命名空间的XPath查询,通过使用XML命名空间管理器和适当的XPath语法来定位和操作XML元素。重点讨论了如何加载XML文档、添加命名空间前缀以及使用XPath表达式进行查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

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_New\Libraries\WHTR.Dao\Accounts\Impls\SqlMap\SuperviseAccount.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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值