问题描述
我正在尝试从 XML 中提取 ReturnRequest
元素,如下所示
var doc = XDocument.Parse(
@"<?xml version=""1.0"" encoding=""utf-8""?>
<RMAStateAckNowledgement xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://XX.ITTS.OA30/digitaldistribution/2012/05"">
<ReturnRequests>
<ReturnRequest>
<RMANumber>RMAXX_201910030001764685</RMANumber>
<StateChangeSuccess>True</StateChangeSuccess>
</ReturnRequest>
</ReturnRequests>
</RMAStateAckNowledgement>");
var ele = doc.Element("ReturnRequests"); // null
var ele2 = doc.Element("ReturnRequest"); // null
var ele3 = doc.Elements("ReturnRequests"); // Enumeration yielded no results
var ele4 = doc.Elements("ReturnRequest"); // Enumeration yielded no results
var ele5 = doc.Descendants("ReturnRequests"); // Enumeration yielded no results
var ele6 = doc.Descendants("ReturnRequest"); // Enumeration yielded no results
我认为这会非常简单,但在代码中,没有一种方法有效。 我错过了什么很明显的东西吗?
更多案例
var ele7 = doc.Root.Elements("ReturnRequests"); // Enumeration yielded no results
var ele8 = doc.Root.Descendants("ReturnRequests"); // Enumeration yielded no results
var ele9 = doc.Root.Elements("ReturnRequest"); // Enumeration yielded no results
var ele10 = doc.Root.Descendants("ReturnRequest"); // Enumeration yielded no results
解决方法
那里有一个非标准的命名空间:
<RMAStateAcknowledgement ... xmlns="http://XX.ITTS.OA30/digitaldistribution/2012/05">
因此,您的所有元素都位于该命名空间中,您需要在查询它们时使用它。
XNamespace ns = "http://XX.ITTS.OA30/digitaldistribution/2012/05";
var ele = doc.Descendants(ns + "ReturnRequests");
如果您想使用 .Element
(仅向下搜索一个级别),您需要查询文档的根元素(“RMAStateAcknowledgement”),而不是文档本身:
XNamespace ns = "http://XX.ITTS.OA30/digitaldistribution/2012/05";
var ele = doc.Root.Element(ns + "ReturnRequests");