Xpath 匹配节点的内容为空(inner text 为空)

本文介绍了一个具体的XML结构案例,并展示了如何使用XPath来选取Title元素为空的节点。文章提供了常见的错误XPath表达式及其修正后的正确表达方式,同时给出了验证程序代码。

需求是从以下写出能从下面的xml中取出Title内容(inner text)为空的节点的XPath:

<?xml version="1.0" encoding="utf-8" ?> <BookCatalog> <Books> <Book> <Title>Asp.net</Title> <Price>22.5</Price> <Author>Abraham</Author> </Book> <Book> <Title></Title> <Price>22.5</Price> <Author>Abraham</Author> </Book> </Books> </BookCatalog>容易写出错误的xPath有:
//Book[Title[text()='']] //Book[Title[text() is null]] //Book[Title[node() is null]] //Book[Title[. is null]] //Book[Title[text()=]] 正确的写法为:
//Book[Title[not(text())]] 或 //Book[Title[not(node())]]

验证程序为:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; namespace TestXPath { class Program { static void Main(string[] args) { string[] errorXPaths = { "//Book[Title[text()='']]", "//Book[Title[text() is null]]", "//Book[Title[node() is null]]", "//Book[Title[. is null]]", "//Book[Title[text()=]]"}; string[] correctXPaths = { "//Book[Title[not(text())]]", "//Book[Title[not(node())]]" }; string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?> " + @" <BookCatalog> <Books> <Book> <Title>Asp.net</Title> <Price>22.5</Price> <Author>Abraham</Author> </Book> <Book> <Title></Title> <Price>22.5</Price> <Author>Abraham</Author> </Book> </Books> </BookCatalog>"; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); foreach (string errorxPath in errorXPaths) { try { XmlNodeList nodeList = xmlDocument.SelectNodes(errorxPath); Console.WriteLine("errorxPath:" + errorxPath); Console.WriteLine("nodeList.Count:" + nodeList.Count); } catch (Exception ex) { Console.WriteLine(ex.Message); } } foreach (string correctXPath in correctXPaths) { XmlNodeList nodeList = xmlDocument.SelectNodes(correctXPath); Console.WriteLine("correctXPath:" + correctXPath); Console.WriteLine("nodeList.Count:" + nodeList.Count); } Console.Read(); } } }


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值