tags:

views:

47

answers:

1

Hello, I'm having an issue using Linq to XML parsing the following XML. What I am doing is getting the element checking if it's what I want, then moving to the next. I am pretty sure it has to do with the xmlns, but I need this code to work with both this style and normal style RSS feeds (no xmlns). Any ideas?

<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://purl.org/rss/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"&gt;
  <channel rdf:about="http://someurl.com"&gt;
    <title>sometitle</title>



XElement currentLocation  = startElementParameter;
            foreach (string x in ("channel\\Title").Split('\\'))
            {
                if (condition1 == false)
                {
                    continue;
                }
                else if (condition2 == false)
                {
                    break;
                }
                else
                {
                    // This is returning null.
                    currentLocation = currentLocation.Element(x);
                }
            }

Thanks!

EDIT: XML didn't paste right.

A: 

The XElement.Element method expects an XName.

You're passing through a string, which means it is being implicitly converted to an XName with no attached namespace.

In other words, your XElement.Element() calls are asking for elements named channel with no namespace, but the channel elements in your example XML are in the http://purl.org/rss/1.0/ namespace due to the xmlns="http://purl.org/rss/1.0/" attribute on <rdf:RDF>.

To pull out the channel elements correctly when a namespace is present, you can do this:

var ns = XNamespace.Get("http://purl.org/rss/1.0/");
currentLocation = currentLocation.Element(ns + "channel");

Using the + operator on an XNamespace and a string creates an XName with an attached namespace.

To support both styles of this document, check whether XDocument.Root has a namespace with the expected URI value. You can use XElement.GetDefaultNamespace() for this.

Leon Breedt