My colleague has given each element in a payload a namespace ns0
for best practice, and my parser stopped working. Reading more on the topic, it seems that declaring each element the namespace is not necessary; it can be set at the root?
When you use multiple namespaces in an XML document, you can define one namespace as the default namespace to create a cleaner looking document. The default namespace is declared in the root element and applies to all unqualified elements in the document. Default namespaces apply to elements only, not to attributes.
Source: https://learn.microsoft.com/en-us/dotnet/standard/data/xml/managing-namespaces-in-an-xml-document
What's the correct approach?
<ns0:Root
xmlns:ns0="urn:asw:erT"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:urn="urn:asw:erT">
<ns0:Ticket
xmlns:urn="urn:asw:erT" Code="TEST" Key="1">
<ns0:client>
<ns0:CardNumber>12345</ns0:CardNumber>
<ns0:OpenPointsBalance>14352</ns0:OpenPointsBalance>
<ns0:PointsEarnedValue>46</ns0:PointsEarnedValue>
<ns0:PointsClosingBalance>14398</ns0:PointsClosingBalance>
</ns0:client>
</ns0:Ticket>
</ns0:Root>
What's the correct approach?
Neither is more correct than the other.
The XML you posted with an explicit namespace prefix for the "urn:asw:erT"
namespace1...
<ns0:Root
xmlns:ns0="urn:asw:erT"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:urn="urn:asw:erT">
<ns0:Ticket
xmlns:urn="urn:asw:erT" Code="TEST" Key="1">
<ns0:client>
<ns0:CardNumber>12345</ns0:CardNumber>
<ns0:OpenPointsBalance>14352</ns0:OpenPointsBalance>
<ns0:PointsEarnedValue>46</ns0:PointsEarnedValue>
<ns0:PointsClosingBalance>14398</ns0:PointsClosingBalance>
</ns0:client>
</ns0:Ticket>
</ns0:Root>
...is fully equivalent to the following XML with a "urn:asw:erT"
default namespace:
<Root xmlns="urn:asw:erT">
<Ticket Code="TEST" Key="1">
<client>
<CardNumber>12345</CardNumber>
<OpenPointsBalance>14352</OpenPointsBalance>
<PointsEarnedValue>46</PointsEarnedValue>
<PointsClosingBalance>14398</PointsClosingBalance>
</client>
</Ticket>
</Root>
No conformant XML processor or application should treat XML Document 1 any differently than XML Document 2.
My colleague has given each element in a payload a namespace
ns0
for best practice
It's fine to use a namespace prefix for each element, but there is no consensus that such is a "best practice".
...and my parser stopped working
If your parser is sensitive to the difference between XML Document 1 and XML Document 2, then your parser is broken.
1 Note:
xmlns:urn="urn:asw:erT"
on ns0:Ticket
is unnecessary but allowed.xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
is also unnecessary but allowed.