SelectNodes始终返回0计数

时间:2017-03-21 08:22:15

标签: c# xml

SelectNodes总是返回0计数,即使它具有值。

    <?xml version="1.0" encoding="utf-16"?>
    <Configurations xmlns="DEH_Common.Schemas">
      <sftpConfiguration>
        <file>
          <filedetails>
            <fileext>csv</fileext>
            <DataContentDetailId>1</DataContentDetailId>
          </filedetails>
    </file>
    </sftpConfiguration>
    </Configurations>

C#读取节点列表....

XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("//Configurations/sftpConfiguration/file");

3 个答案:

答案 0 :(得分:2)

这是因为在xml中使用了命名空间,你应该将命名空间添加到xmlDoc and also no need to use DocumentElement`这段代码可以工作:

var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("a", "DEH_Common.Schemas");
XmlNodeList nodeList = xmlDoc.SelectNodes("//a:sftpConfiguration/a:file", nsmgr);

答案 1 :(得分:1)

在您的XML DocumentElement中是Configurations节点,因此您的XPath应为sftpConfiguration/file

XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("sftpConfiguration/file");

答案 2 :(得分:0)

试试这个:

xmlDoc.DocumentElement.SelectNodes("/Configurations[@*]/sftpConfiguration/file");