开发者

C# XPathSelectElement returns null

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开发者_JAVA技巧, 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜