Brad B. Brad B. - 10 days ago 6
C# Question

What have I done wrong here with checking for xml nodes that don't exist?

My XML:

<?xml version='1.0'?>
<bookstore xmlns="urn:newbooks-schema">
<book genre="novel" style="hardcover">
<title>The Handmaid's Tale</title>
<author>
<first-name>Margaret</first-name>
<last-name>Atwood</last-name>
</author>
<price>19.95</price>
</book>
</bookstore>


My program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace MoreXMLTesting
{
class Program
{
static void Main(string[] args)
{
//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.Load("newbooks.xml");

if (doc.SelectSingleNode("/bookstore/book/title") == null)
{
Console.WriteLine("Whelp, there aren't any new books");
}
if (doc.SelectSingleNode("/bookstore/coffee") == null);
{
Console.WriteLine("There ain't coffee at this joint");
}

Console.ReadKey();
}
}
}


I would have thought that I'd get the output of "There ain't coffee at this joint, but I also get "Whelp, there aren't any new books." What have I done wrong here with checking for xml nodes that don't exist?

EDIT:

Struggling with another aspect. What happens when there is a sub-namespace?

<?xml version='1.0'?>
<bookstore xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="C:\newbooks.xsd">
<book genre="novel" style="hardcover">
<title>The Handmaid's Tale</title>
<author>
<first-name>Margaret</first-name>
<last-name>Atwood</last-name>
</author>
<price>19.95</price>
</book>
</bookstore>

Answer

You need to respect and deal with the XML namespace in your XML document!

<bookstore xmlns="urn:newbooks-schema">
           ***************************

Try this code:

// Create the XmlDocument.
XmlDocument doc = new XmlDocument();

// Create the XML Namespace Manager and initialize it    
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ns", "urn:newbooks-schema");

doc.Load("newbooks.xml");

// *USE* the namespace prefix as defined by your "nsmgr" in your XPath
if (doc.SelectSingleNode("/ns:bookstore/ns:book/ns:title", nsmgr) == null)
{
    Console.WriteLine("Whelp, there aren't any new books");
}

if (doc.SelectSingleNode("/ns:bookstore/ns:coffee", nsmgr) == null) ;
{
    Console.WriteLine("There ain't coffee at this joint");
}