Ignore Whitespace when working with SelectSingleNode and Xpath



Let's assume we have the following xml file



<?xml version="1.0" encoding="utf-8"?>
<bookstore>
<book genre="novel" publicationdate="1997" ISBN="1-861001-57-8">
<title>Pride And Prejudice</title>
<author>
<first-name>Jane</first-name>
<last-name>Austen</last-name>
</author>
<price>24.95</price>
</book>
<book genre="textbook" publicationdate="2013" ISBN="1-861002-30-1">
<title>Head First C#</title>
<author>
<first-name>Jennifer</first-name>
<last-name>Greene</last-name>
</author>
<price>29.95</price>
</book>
</bookstore>


I want to check if the element book with the attribute genre="novel" exist and if not add it.


I've written the following code and it works beautifully. However, if someone edits the xml file and accidentally places an extra space between the word "novel" and the double quotes, genre=" novel ", or let's say I'm an idiot and added the extra space when creating the attribute's value the xpath won't be valid any more and the code will add a node when one already exists. Is there a way to use SelectSingleNode in a way that it will ignore whitespace?



XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Users\anonymous\Documents\file.xml");

string xpath = @"/bookstore/book [@genre='novel']";
var rootNode = doc.SelectSingleNode(@"/bookstore");
var bookNode = doc.SelectSingleNode(xpath);

if (bookNode == null)
{
XmlNode newNode = doc.CreateElement("book");
XmlAttribute genreAttribute = doc.CreateAttribute("genre");
genreAttribute.Value = @"novel";
newNode.Attributes.Append(genreAttribute);
rootNode.AppendChild(newNode);
}
doc.Save(@"C:\Users\anonymous\Documents\file.xml");

No comments:

Post a Comment