Lord Vermillion
Lord Vermillion

Reputation: 5424

XmlTypeAttribute works only on attributes in class

I'm trying to parse this to XML using webservice:

[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.xx.com/zz/Domain")]
Public class A 
{
   public int element1;
   public int element2;
}

This gives

<A>
 <element1 xlmns="http://www.xx.com/zz/Domain">1</element1>
 <element2 xlmns="http://www.xx.com/zz/Domain">1</element1>
</A>

What should i use instead of XmlTypeAttribute to get

<A xlmns="http://www.xx.com/zz/Domain">
 <element1>1</element1>
 <element2>1</element1>
</A>

Upvotes: 1

Views: 1470

Answers (1)

samy
samy

Reputation: 14972

Use the XmlRoot attribute instead:

[XmlRoot( Namespace = "http://www.xx.com/zz/Domain")>
Public class A 
{
    public int element1;
    public int element2;
}

EDIT: regarding your comment, could you give your serialization method? I think there may be something there since the following:

[XmlRoot(Namespace = "http://www.xx.com/zz/Domain")]
public class RootA
{
   public int element1;
   public int element2;
}

[XmlType(Namespace = "http://www.xx.com/zz/Domain")]
public class TypeA
{
    public int element1;
    public int element2;
}

internal class Program
{
    private static void Main(string[] args)
    {
        Serialize<TypeA>();
        Serialize<RootA>();
        Console.ReadLine();
    }

    public static void Serialize<T>() where T : new() 
    {
        Console.WriteLine();
        Console.WriteLine();
        var serializable = new T();
        System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(serializable.GetType());
        Console.WriteLine(serializable.GetType().Name);
        x.Serialize(Console.Out, serializable);
        Console.WriteLine();
        Console.WriteLine();
    }
}

outputs the expected result:

TypeA
<?xml version="1.0" encoding="ibm850"?>
<TypeA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://w
ww.w3.org/2001/XMLSchema">
  <element1 xmlns="http://www.xx.com/zz/Domain">0</element1>
  <element2 xmlns="http://www.xx.com/zz/Domain">0</element2>
</TypeA>



RootA
<?xml version="1.0" encoding="ibm850"?>
<RootA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://w
ww.w3.org/2001/XMLSchema" xmlns="http://www.xx.com/zz/Domain">
  <element1>0</element1>
  <element2>0</element2>
</RootA>

Upvotes: 1

Related Questions