views:

459

answers:

1

I'm trying to get an XML file generated using a namespace as such:

<namespace:Example1>
    <namespace:Part1>Value1</namespace:Part1>
</namespace:Example1>

I've tried using

    [XmlAttribute(Namespace = "namespace")]
    public string Namespace { get; set; }

but I'm clearly missing something. The structure I've used is

[XmlRoot("Example1")]
public class Blah 
{
    [XmlAttribute(Namespace = "namespace")]
    public string Namespace { get; set; }

but all I get is

<Example1>
    <Part1>Value1</Part1>
</Example1>

Any help would be greatly appreciated.

Edit:

[XmlRoot(ElementName="Chart2",  Namespace="vc")]

doesn't work.

A: 

You can use the XmlSerializerNamespaces class to add the prefix for a given namespace in the xml.

I hope the below code will he you better.

    [XmlRoot(ElementName = "Example1")]
        public class Blah
        {
            public string Part1 { get; set; }
        }

            Blah bl = new Blah();
            bl.Part1 = "MyPart1";
            // Serialization

            /* Create an XmlSerializerNamespaces object and add two prefix-namespace pairs. */
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("namespace", "test");

            XmlSerializer s = new XmlSerializer(typeof(Blah),"test");
            TextWriter w = new StreamWriter(@"c:\list.xml");
            s.Serialize(w, bl,ns);
            w.Close();
/* Output */
<?xml version="1.0" encoding="utf-8"?>
<namespace:Example1 xmlns:namespace="test">
  <namespace:Part1>MyPart1</namespace:Part1>
</namespace:Example1>
Gabriel Susai