3

I'm creating XML document using XDocument in C#. I have a question.

Is

<Simple xmlns = "Example"></Simple>

equivalent to

<Example:Simple></Example:Simple>

?

I tried to get second solution with XNamespace and XElement in C#, but I get only first.

4 Answers 4

6

No.

The first example creates a Simple element in the Example namespace (note that namespaces are usually expressed as URIs)

The second example creates a Simple element in whatever namespace is associated with the Example prefix (as defined by an xmlns attribute).

These would be equivalent:

<xml xmlns="http://example.com/myNameSpace">
    <Simple></Simple>
</xml>

<xml xmlns="http://example.com/myNameSpace" xmlns:Example="http://example.com/myNameSpace">
    <Example:Simple></Example:Simple>
</xml>
1
  • 1
    Namespaces are always expressed as URI-references. They're usually expressed as absolute URI-references rather than relative as in the question, so they don't change meaning.
    – Jon Hanna
    Aug 16, 2012 at 13:03
1

In the first example, you have defined a default namespace which applies to any element/attribute that is not prefixed with its own namespace.

In the second example, you have not defined a namespace.

1

No, because xml namespaces allow for characters which aren't supported by element names, you can't prefix an element tag name with its namespace like that.

Add a namespace prefix, like so:

<alias:Simple xmlns:alias = "Example"></alias:Simple>
1

No, but it's equivalent to:

<Example:Simple xmlns:Example="Example"></Example:Simple>

It's a bad idea to use relative URIs as the namespace name, since this XML now has a different namespace depending on where it came from. So always give the full URI. E.g if the XML was being received from http://example.net/somePlace/someXML then the relative URI Example expands to http://example.net/somePlace/Example, so use it fully:

<Example:Simple xmlns:Example="http://example.net/somePlace/Example"></Example:Simple>

OR

<Simple xmlns="http://example.net/somePlace/Example"></Simple>

Otherwise if someone saved it in C:\Documents then on opening it again it becomes the equivalent to:

<Simple xmlns="file:///C|/Documents/Example"></Simple>

Which means that the meaning of Simple here is completely different to that when it was first downloaded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.