views:

79

answers:

1

In a project I am working on, I just finished writing an XSD for my XML so other engineers could work on the XML easier. Along with this XSD came XML namespaces. In my current parsing code, I have been using something like this:

XElement element = xmlRoot.Element(XML.ELEMENT_NAME);

With XML being a class full of constants that is used throughout the program for XML input and output. But, now that namespaces are being used, this doesn't work anymore. The obvious, but barely elegant, solution is to go in and make all of the parsing code look like this:

XElement element = xmlRoot.Element(XML.NAMESPACE + XML.ELEMENT_NAME);

Thinking about it more, it would look a lot better to go off and define an extension method to add in this namespace and return the XElement. This idea would get the code looking something like this:

XElement element = xmlRoot.GetMyElement(XML.ELEMENT_NAME);

These ideas are what I have come up with so far to deal with the namespace issue. Basically, my question here is this:
Is there a better method for parsing XElements with a known, constant namespace? If so, what is it?

A: 

Well, no one's provided an alternative, and I've already implemented this in the code. So, I'm going to go ahead and put this in as an answer so I can close this out.

I went ahead and used the extension method that automatically added in the namespace. Note that this only works if you have a constant namespace! Otherwise, you may want to add another argument to your extension method simply to avoid doing the weird namespace concatenation.

      public static XElement
      GetNamespaceElement(this XElement element, string ns, string name)
      {
          XNamespace n = new XNamespace();
          n.NamespaceName = ns;
          return element.Element(n + name);
      }
fire.eagle