Search code examples
c#xmllinqxelement

XElement and it's attributes


I've been looking for clarification between XName , XNamespace & XElement.Name.LocalName , from msdn.microsoft.com the example states that

  XNamespace ns = "http://www.adventure-works.com";
  XElement root = new XElement(ns + "Root", "content");
  Console.WriteLine(root.Name);

Q. Does Xelement has to have a namespace necessarily?

When I use it like:

 XElement xEle = XElement.Parse(xml);
 String tagName = xEle.Name.LocalName;

It gives the first Element's Name, why?

(Please clarify if possible the difference & possible usage of XElement.XName & XElement.XName.LocalName)


Solution

  • An XElement has a name, represented as an XName. That XName may or may not have a namespace associated with it. If it doesn't, the XName.Namespace property will return XNamespace.None.

    An XName is a fully-qualified name, basically - whereas XName.LocalName will only give the local part.

    So in your example:

    • The local name is Root
    • The namespace URI is http://www.adventure-works.com

    The XName with a namespace is not the same as an XName without a namespace (or with a different namespace). So for example, the Element(XName) method will not find an element with a name with the specified local name but a different namespace.