【问题标题】:XML LINQ query returns no dataXML LINQ 查询不返回任何数据
【发布时间】:2010-12-16 08:48:52
【问题描述】:

我今天尝试使用 LINQ to XML,但不是很成功。 当我使用命名空间时,我没有得到任何数据。

这是(简化的)xml:

<?xml version="1.0" encoding="UTF-8" ?>
<Message xmlns="urn:protocols:format13">
    <data>
    testdata
    </data>
</Message>

我尝试使用(xmlmsg 是一个字符串)获取数据:

XElement root = XElement.Parse(xmlmsg);
XNamespace ns = root.Attribute("xmlns").ToString();

List<XElement> datalist =
       (from desc in root.Descendants(ns + "data")
         select desc).ToList<XElement>();

但数据列表仍然为空。如果我不使用命名空间,它就可以工作。

我之前使用过 XmlReader,它在命名空间中运行良好。但是由于我的 xml 数据解析起来有点复杂,所以我想使用 LINQ。

有什么提示吗?

【问题讨论】:

    标签: c# linq .net-3.5 linq-to-xml xml-namespaces


    【解决方案1】:
            XNamespace ns = root.Name.Namespace;
    
            List<XElement> datalist =
                   (from desc in root.Descendants(ns + "data")
                    select desc).ToList<XElement>();
    

    或者为什么它不起作用;您没有访问属性的 value;这也有效:

    XNamespace ns = (string)root.Attribute("xmlns");
    

    XNamespace ns = root.Attribute("xmlns").Value;
    

    【讨论】:

    • 谢谢,root.Name.Namespace 确实有效。 XNamespace ns = root.Attribute("xmlns").ToString();看起来很像 XNamespace ns = (string)root.Attribute("xmlns");
    猜你喜欢
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    相关资源
    最近更新 更多