3

I know this might be a very basic question, but I'm new to XML serialization and spent hours trying to read different pages.

PS: this is a programming language independent question.

2 Answers 2

6

Simple answer: you don't.

If you're serializing data as XML then you have to agree the details of the XML vocabulary with the consumers of the data. Perhaps you define it yourself, perhaps your consumers define it, perhaps it's defined by some standards body. Whichever is the case, whoever defines the vocabulary has the choice either to use namespaces or not to use them. Some XML designers use namespaces when they aren't really necessary. They can be useful if ever anyone wants to design composite documents that include a mixture of different XML vocabularies, but this doesn't happen as often as people imagine, and very often, the complexity of using namespaces doesn't achieve any real benefits. On the other hand, it does help to future-proof your design against unforeseen changes in future requirements.

1
  • Great answer, wish this was more common knowledge. Overuse of namespaces has really hindered XML adoption. Apr 10, 2016 at 19:53
4

To build on Michael's answer, namespaces solve conflicts. So, if you have no conflicts you don't need them.

If I had XML from two sources:

Source 1:
<Foobar>
  <Name>Foo</Name>
</Foobar>
Source 2:
<Foobar>
  <FullName>Foo</FullName>
</Foobar>

How can I determine which Foobar? With namespaces.

xmlns:a="http://www.fooOnMe.org/"
xmlns:b="http://www.fooOnU.org/"

   Source 1:
    <a:Foobar>
      <a:Name>Foo</a:Name>
    </a:Foobar>
    Source 2:
    <b:Foobar>
      <b:FullName>Foo</b:FullName>
    </b:Foobar>

Most of the time, if the XML is coming from a single source, no namespaces are required because there are no conflicts, but people use them anyway to no real effect. If this is the case, you must include them in your xPath queries, etc. or nothing will be returned. If your composing an XML document from multiple sources, it is best to include them to avoid the potential for conflicts, but this is a distinct use case.

1
  • This may help determine which "Foobar," but what about "Barf, ew?"
    – bubbleking
    Feb 21, 2016 at 16:54

Your Answer

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

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