Question

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)

Was it helpful?

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.

OTHER TIPS

Q. Does Xelement has to have a namespace necessarily?

No.

It gives the first Element's Name, why?

Because you are parsing your XML and getting the root element that contains all elements.So it is giving you the root element's name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top