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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With