Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

c# - LINQ to XML Elements() and Descendants() yielded no results even the elements do exist

I'm trying to extract ReturnRequest elements from the XML like below

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

I thought it would be very straightforward but as in the code, none of the approaches works. Did I miss something very obvious?

Few more cases

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You've got a non-standard namespace there:

<RMAStateAcknowledgement ... xmlns="http://XX.ITTS.OA30/digitaldistribution/2012/05">

Therefore all of your elements live in that namespace, and you need to use that when querying them.

XNamespace ns = "http://XX.ITTS.OA30/digitaldistribution/2012/05";
var ele = doc.Descendants(ns + "ReturnRequests");

If you want to use .Element (which only searches down a single level), you need to be querying the root element of the document ("RMAStateAcknowledgement"), not the document itself:

XNamespace ns = "http://XX.ITTS.OA30/digitaldistribution/2012/05";
var ele = doc.Root.Element(ns + "ReturnRequests");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...