Click here to Skip to main content
15,558,870 members
Please Sign up or sign in to vote.
4.33/5 (4 votes)
See more:
Hi,

I use the XmlSerializer and I'm looking for a way to set the default XML namespace on the top level Element. The correct way to do this, I hoped, was to specify this in an XmlType attribibute on the top level class. However, the namespace is only applied to the children of this class. For example, see the C# code below that serializes a simple nested structure:

// Contained class.<br />    public class Circle<br />    {<br />    }<br /><br />    // Container class.<br />    [XmlType(Namespace="http://mbshapes.com")] // Why does the Shapes element not use this namespace?<br />    public class Shapes<br />    {<br />        private Circle _circle = new Circle();<br /><br />        public Circle Circle<br />        {<br />            get<br />            {<br />                return _circle;<br />            }<br />            set<br />            {<br />                _circle = value;<br />            }<br />        }<br />    }<br /><br />    // Serialize Shapes object.<br />    public class SerializeTest<br />    {<br />        public static void Serialize()<br />        {<br />            // Create Shapes object.<br />            Shapes shapes = new Shapes();<br /><br />            // Open file.<br />            using (TextWriter textWriter = new StreamWriter("Shapes.xml"))<br />            {                <br />                // Serialize.<br />                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Shapes));<br />                xmlSerializer.Serialize(textWriter, shapes);<br />            }<br />        }<br />    }


The output is this:

<?xml version="1.0" encoding="utf-8"?><br /><Shapes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><br />  <Circle xmlns="http://mbshapes.com" /><br /></Shapes>


What I expected (and what I need), is something like this:

<br /><?xml version="1.0" encoding="utf-8"?><br /><Shapes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://mbshapes.com"><br />  <Circle /><br /></Shapes><br />


Am I doing something wrong? Or are there any work-arounds?

Thanks.
Posted

1 solution

Try
[<code>XmlRoot</code>(Namespace = "http://mbshapes.com")]<br />    public class Shapes<br />    {<br />        private Circle _circle = new Circle();<br /><br />        public Circle Circle<br />        {<br />            get<br />            {<br />                return _circle;<br />            }<br />            set<br />            {<br />                _circle = value;<br />            }<br />        }<br />    }


 
Share this answer
 
  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900