How to get an specific node in xml with namespaces

2019-08-22 09:48发布

问题:

I'm dealing to access an specific node from a XML Document. I realized that this one as a base namespace. Here is the example.

I'm interested to get the value of the node d:MediaUrl from all descendents node (entry). And I haven't accomplished that.

When I debug the variable iterator 'i', I can see that the XML includes the default namespace again, something like:

<entry xmlns="http://schemas.microsoft.com.ado/..." 

And also I have to include the another namespace called 'd'.

What can I do to access to that particular nodes?

This is what I have.

        var doc = XDocument.Parse(result);

        string BASE_NS = "http://www.w3.org/2005/Atom";

        string d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
        var query = from i in doc.Descendants(XName.Get("entry", BASE_NS))
                    select new Image()
        {
            Url = i.Element(XName.Get("MediaUrl", BASE_NS)).Value
        };

        var results = query.ToList();

回答1:

I would suggest using XNamespace rather than XName (personal preference, mainly - as that's how I've always dealt with namespaces in LINQ to XML). To me it's less effort to set up the namespaces in advance and then use Element(NS + "element name") than to useXName.Get(though usingXName.Get` is perfectly fine if that's what you want to do.

If you want to get a all the "MediaUrl" elements for each entry, then I'd do something like this:

XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";

var query = (from i in doc.Descendants(d + "MediaUrl")
             select new Image()
             {
                 Url = i.Value
             }).ToList();

If you want to get only one of them, then you need to do something a little different, depending on which one you wanted to get.

For the properties MediaUrl:

XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

var query = (from i in doc.Descendants(m + "properties")
             select new Image()
             {
                 Url = i.Element(d + "MediaUrl").Value
             }).ToList();

For the Thumbnail MediaUrl:

XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";

var query = (from i in doc.Descendants(d + "Thumbnail")
             select new Image()
             {
                 Url = i.Element(d + "MediaUrl").Value
             }).ToList();

The key here is to use the namespace in conjunction with the element name in order to retrieve it.



回答2:

var query = from i in doc.Descendants("{full namespace for prefix d}MediaUrl")
                    select new Image()
        {
            Url = i.Value
        };