【问题标题】:LINQ xml finding nodes returns nullLINQ xml 查找节点返回 null
【发布时间】:2018-01-15 10:14:28
【问题描述】:

我尝试使用 XDocument 类解析 xml 文件,其条件是如果子节点与给定字符串匹配,则选择其父节点。

<SalesQuotes xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://api.some.com/version/1">
  <Pagination>
    <NumberOfItems>2380</NumberOfItems>
    <PageSize>200</PageSize>
    <PageNumber>1</PageNumber>
    <NumberOfPages>12</NumberOfPages>
  </Pagination>
  <SalesQuote>
    <Guid>825634b9-28f5-4aa7-98e7-5e4a4ed6bc6a</Guid>
    <LastModifiedOn>2018-01-09T12:23:56.6133445</LastModifiedOn>
    <Comments>Please note:
installation is not included in this quote
    </Comments>
  </SalesQuote>
</SalesQuotes>

我尝试过使用

var contents = File.ReadAllText(path: "test1.xml");
var doc = XDocument.Parse(contents);
var root = doc.Root;
var sq = root.Elements("SalesQuote");//return null

var theQuote = root.Elements("SalesQuote").Where(el => el.Element("Guid").Value == "825634b9-28f5-4aa7-98e7-5e4a4ed6bc6a");//return null

var theAlternativeQuote =
            from el in doc.Descendants("SalesQuote").Elements("Guid")
            where el.Value == "825634b9-28f5-4aa7-98e7-5e4a4ed6bc6a"
            select el;//return null

我似乎找不到问题所在。

非常感谢任何帮助!谢谢。

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:

    你忽略了命名空间兄弟。

    请删除 XML 中的 xmlns 属性或试试这个:

    var contents = File.ReadAllText("XMLFile1.xml");
    var doc = XDocument.Parse(contents);
    var root = doc.Root;
    XNamespace ns = "http://api.some.com/version/1";
    var sq = root.Descendants(ns + "SalesQuotes"); //return null
    
    var theQuote = root.Elements(ns + "SalesQuote")
        .Where(el => el.Element(ns + "Guid").Value == "825634b9-28f5-4aa7-98e7-5e4a4ed6bc6a"); //return null
    
    var theAlternativeQuote =
        from el in doc.Descendants(ns + "SalesQuote").Elements(ns + "Guid")
        where el.Value == "825634b9-28f5-4aa7-98e7-5e4a4ed6bc6a"
        select el; //return null
    

    【讨论】:

      【解决方案2】:

      如果您不太关心保持当前的实现,您可以考虑使用类型化数据集并将您的 XML 加载到完全类型化的结构化对象中。

      使用 Linq 查询这些对象将比我在您当前的实现中看到的更直接。

      您可能还会发现这很有用: SO Question: Deserialize XML Document to Objects

      【讨论】:

        【解决方案3】:

        是的,您缺少可以使用 document.Root.GetDefaultNamespace() 获取的命名空间

            // Load
            var document = XDocument.Parse(xml);
            var xmlns = document.Root.GetDefaultNamespace();
        
            // Find
            var query = from element in document
                            .Descendants(xmlns + "SalesQuote")
                            .Elements(xmlns + "Guid")
                        where element.Value == "825634b9-28f5-4aa7-98e7-5e4a4ed6bc6a"
                        select element;
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-31
        • 1970-01-01
        • 1970-01-01
        • 2017-10-21
        • 2013-01-19
        • 1970-01-01
        • 2019-08-05
        相关资源
        最近更新 更多