Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# XPathSelectElement returns null

Tags:

c#

xpath

I am trying to use the XPathSelectElement method of the System.Xml.XPath namespace but for some reason it always returns null, and I have no idea why.

Here is the code:

TextReader stream = new StreamReader("config.ini");
XmlReader reader = XmlReader.Create(stream);
XElement xml = XElement.Load(reader);

XElement file = xml.XPathSelectElement("Config/File");

Here is the XML file it is trying to read:

<?xml version="1.0" encoding="utf-8"?>
<Config>
 <File>serp_feed.xml</File>
</Config>

I have tried many things (adding a namespace table, changing the XPath, etc.) but nothing works!

Any ideas?

like image 997
TheBoss Avatar asked Nov 16 '10 13:11

TheBoss


2 Answers

Well with XElement.Load the variable named xml is the root element, the "Config" element of the XML sample you posted. And if you use the path Config/File on that element as the context node you are looking for a child element named "Config" having a descendant "File" element. The "Config" element does not have a "Config" child element, it only has a "File" child element. So you want the XPath File or you need XDocument xml = XDocument.Load("config.ini), then your path works.

like image 153
Martin Honnen Avatar answered Sep 28 '22 06:09

Martin Honnen


Try

XElement file = xml.XPathSelectElement("File")

Because you are using XElement.Load rather than XDocument.Load the root will be the element rather that the document, hence the step in the XPath expression is not required.

like image 36
Nick Jones Avatar answered Sep 28 '22 07:09

Nick Jones