XmlTypeAttribute works only on attributes in class

前端 未结 1 930
春和景丽
春和景丽 2021-01-26 18:56

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

[System.Xml.Serialization.XmlTypeAttribute(Namespace=\"http://www.xx.com/zz/Domain\")]
Public class A 
{
   pu         


        
相关标签:
1条回答
  • 2021-01-26 19:32

    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>
    
    0 讨论(0)
提交回复
热议问题