XmlTypeAttribute仅适用于类中的属性

时间:2014-10-23 13:41:21

标签: c# xml wcf

我正在尝试使用webservice将其解析为XML:

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

这给出了

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

我应该使用什么而不是XmlTypeAttribute来获取

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

1 个答案:

答案 0 :(得分:1)

请改为使用XmlRoot属性:

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

编辑:关于你的评论,你能给出你的序列化方法吗?我认为从那以后可能会有一些东西:

[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();
    }
}

输出预期结果:

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>