LINQ xml查找节点返回null

Isa*_*c L 4 c# xml linq

我尝试使用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>
Run Code Online (Sandbox Code Playgroud)

我试过用

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
Run Code Online (Sandbox Code Playgroud)

我似乎无法找到什么是错的.

任何帮助深表感谢!谢谢.

Fer*_*yan 6

您忽略了名称空间兄弟.

请删除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
Run Code Online (Sandbox Code Playgroud)