需求是从以下写出能从下面的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(); } } }
本文介绍了一个具体的XML结构案例,并展示了如何使用XPath来选取Title元素为空的节点。文章提供了常见的错误XPath表达式及其修正后的正确表达方式,同时给出了验证程序代码。
644

被折叠的 条评论
为什么被折叠?



