I have an object generated by an “Add service reference…” operation and I am manually serializing it with a generic serializer I wrote.
My problem is that the data contract has some internal objects.
The serializer adds an empty namespace atribute to the starting tag of the internal objects. Is there any way to stop this from happening?
What about making your internal objects belong to the same namespace as the root? That way, it would be correct to omit the
xmlnsdeclaration from the descendants. You can use the[assembly: ContractNamespace]attribute to override the namespace for all contracts in your assembly. Refer to Data Contract Names for an example.Edit: An elaboration with some examples below.
Suppose you’re constructing an XML document manually, and don’t specify a namespace for any of your elements.
The generated XML would, as expected, be void of namespace declarations:
If, however, you specify a namespace just for your root element, then all child elements must explicitly revert out of that default namespace, using the
xml=""declaration. Per the Namespace Defaulting rules:Thus, the following code (having a namespace specified for the root element)…
…would give the following XML:
Note how the children of the
<Publisher>element do not need to revert out of the root’s namespace, since they inherit the “no namespace” declaration from their parent.To eliminate the
xmlns=""declarations, we could, for the sake of the demonstration, assign the same namespace to all descendants:This would give an XML document with the namespace declared in just the root (and implicitly inherited in all descendants):
To mimic your scenario involving a web service, we can create the following WCF service.
We add a service reference to the above service in our client application, consume its operation, and serialize the result whilst enclosing it in a root
Bookselement having an explicit namespace:In this case, the inner element
Bookcontains anxmlns=""declaration.As explained above, this
xmlns=""can be eliminated by setting theBookelement’s namespace (and that of its descendants) to correspond to the root’s. For theXmlSerializerclass, the default namespace for all elements can be specified through the second parameter to its constructor. (The actual technique would vary depending on which serialization strategy you’re using.)And that would give the expected result: