The requirement is to write the XPath that can retrieve the node with the title content (inner text) empty from the following 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>
The XPath statements that are easy to write are as follows:
//Book[Title[text()='']] //Book[Title[text() is null]] //Book[Title[node() is null]] //Book[Title[. is null]] //Book[Title[text()=]]
The correct syntax is as follows:
// Book [title [not (text ()] or // book [title [not (node ()]
The validators are:
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(); } }}