Xpath 匹配节点的内容为空(inner text 为空)
需求是从以下写出能从下面的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>
<?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[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())]]
//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();
- }
- }
- }