C # XPathSelectElement returns null

I'm 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 that he is trying to read:

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

I tried a lot of things (adding a namespace table, changing XPath, etc.), but nothing works!

Any ideas?

+4
source share
2 answers

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

+9
source

Try

 XElement file = xml.XPathSelectElement("File") 

Since you are using XElement.Load and not XDocument.Load , the element will be the root, not the document, so no step in the XPath expression is required.

+3
source

All Articles