XPathSelectElements 返回 null [英] XPathSelectElements returns null

查看:34
本文介绍了XPathSelectElements 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

加载函数已经在xmlData类中定义

Load function is already defined in xmlData class

public class XmlData
{
    public void Load(XElement xDoc)
    {
        var id = xDoc.XPathSelectElements("//ID");
        var listIds = xDoc.XPathSelectElements("/Lists//List/ListIDS/ListIDS");
    }
}

我只是从我这边调用 Load 函数.

I'm just calling the Load function from my end.

            XmlData aXmlData = new XmlData();

            string input, stringXML = "";
            TextReader aTextReader = new StreamReader("D:\\test.xml");
            while ((input = aTextReader.ReadLine()) != null)
            {
                stringXML += input;
            }
            XElement Content = XElement.Parse(stringXML);
            aXmlData.Load(Content);

在加载函数中,我将 id 和 listIds 都设为 null.

in load function,im getting both id and and listIds as null.

我的 test.xml 包含

My test.xml contains

<SEARCH>
  <ID>11242</ID>
  <Lists>
    <List CURRENT="true" AGGREGATEDCHANGED="false">
      <ListIDS>
        <ListID>100567</ListID>
        <ListID>100564</ListID>
        <ListID>100025</ListID>
        <ListID>2</ListID>
        <ListID>1</ListID>
      </ListIDS>
    </List>
  </Lists>
</SEARCH>

推荐答案

您的示例 XML doesn't 在命名空间中具有 id 元素和 nss 别名.在这种情况下,它将是 ,或者会设置一个默认的命名空间.对于这个答案,我假设实际上您要查找的元素 在命名空间中.

Your sample XML doesn't have an id element in the namespace with the nss alias. It would be <nss:id> in that case, or there'd be a default namespace set up. I've assumed for this answer that in reality the element you're looking for is in the namespace.

您的查询试图在根级别查找名为 id 的元素.要查找所有 id 元素,您需要:

Your query is trying to find an element called id at the root level. To find all id elements, you need:

var tempId = xDoc.XPathSelectElements("//nss:id", ns);

...虽然我个人会使用:

... although personally I'd use:

XDocument doc = XDocument.Parse(...);
XNamespace nss = "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner";
// Or use FirstOrDefault(), or whatever...
XElement idElement = doc.Descendants(nss + "id").Single();

(我更喜欢在 LINQ to XML 类型上使用查询方法而不是 XPath...我发现更容易避免愚蠢的语法错误等)

(I prefer using the query methods on LINQ to XML types instead of XPath... I find it easier to avoid silly syntax errors etc.)

您的示例代码也不清楚,因为您使用的是尚未声明的 xDoc...它有助于编写完整示例,理想情况下包括所需的一切编译并作为控制台应用程序运行.

Your sample code is also unclear as you're using xDoc which hasn't been declared... it helps to write complete examples, ideally including everything required to compile and run as a console app.

这篇关于XPathSelectElements 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆