all groups > dotnet xml > february 2007 >
You're in the

dotnet xml

group:

Adding namespace prefix to Root node


Adding namespace prefix to Root node scottpet NO[at]SPAM gmail.com
2/28/2007 1:35:43 PM
dotnet xml:
Hi,

I want to add a namespace prefix to the root node of an object I am
serializing to XML.

I have been reading though this article:
http://msdn2.microsoft.com/en-gb/library/system.xml.serialization.xmlnamespacedeclarationsattribute.aspx

I get namespace prefixes in the document, but not on the root node.
Specifically, the serializer does not work as described in the last
paragraph:

(from http://msdn2.microsoft.com/en-gb/library/system.xml.serialization.xmlnamespacedeclarationsattribute.aspx)

" For example, in the following XML document, only the prefix pair
"cal" is captured, but not the "x" prefix. To get that data, add a
member with the XmlNamespaceDeclarationsAttribute to the class that
represents the root element."

If you look through the sample, they already use the
XmlNamespaceDeclarationsAttribute and there is no way to associate the
instance of the XmlNamespaceDeclarationsAttribute with the root node.

Is this a bug or a feature?

Thanks -Scott
Re: Adding namespace prefix to Root node scottpet NO[at]SPAM gmail.com
2/28/2007 2:04:32 PM
Ok..figured it out...you have to load the resulting document into an
XmlDocument type, then use the DocumentElement.Prefix property to set
the prefix of the root node...works perfectly. It's unfortunate to
have to do that since that is a common scenario.
Re: Adding namespace prefix to Root node Martin Honnen
3/1/2007 2:11:12 PM
[quoted text, click to view]

Here is an example doing that:

XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add("prefix", "http://example.com/2007/ns1");
XmlSerializer serializer = new XmlSerializer(typeof(Example));

Example example = new Example();
example.Name = "Kibo";
example.Power = 42;
serializer.Serialize(Console.Out, example, namespaces);
Console.WriteLine();

[XmlRoot(Namespace = "http://example.com/2007/ns1")]
public class Example {
public Example () {}
public string Name;
public int Power;
}


The output is:

<prefix:Example xmlns:prefix="http://example.com/2007/ns1">
<prefix:Name>Kibo</prefix:Name>
<prefix:Power>42</prefix:Power>
</prefix:Example>


Is that what you want to achieve? Or do you want the namespace only on
the root element? Then you need to use e.g.

[XmlRoot(Namespace = "http://example.com/2007/ns1")]
public class Example {
public Example () {}
[XmlElement(Namespace = "")]
public string Name;
[XmlElement(Namespace = "")]
public int Power;
}


--

Martin Honnen --- MVP XML
AddThis Social Bookmark Button