开发者

c# WCF getting list of elements values

开发者 https://www.devze.com 2023-04-04 01:02 出处:网络
I have a piece of XML example below <job> <refno>XXX</refno> <specialisms> <specialism>1</specialism>

I have a piece of XML example below

<job>
   <refno>XXX</refno>
   <specialisms>
       <specialism>1</specialism>
       <specialism>2</specialism>
   </specialisms>
</job>

How using WCF c# do I serialise these values into a list?

I currently开发者_StackOverflow社区 have...

[DataMember]
public SpecialismList specialisms { get; set; }

[CollectionDataContract(Name = "specialisms", ItemName = "specialism")]
public class SpecialismList : List<int> { }

But it isn't currently working... any tips?


This data contract should work out just fine to serialize to the XML you posted (see code below). What is the problem you're having?

public class StackOverflow_7386673
{
    [DataContract(Name = "job", Namespace = "")]
    public class Job
    {
        [DataMember(Order = 0)]
        public string refno { get; set; }
        [DataMember(Order = 1)]
        public SpecialismList specialisms { get; set; }
    }

    [CollectionDataContract(Name = "specialisms", ItemName = "specialism", Namespace = "")]
    public class SpecialismList : List<int> { }

    public static void Test()
    {
        MemoryStream ms = new MemoryStream();
        DataContractSerializer dcs = new DataContractSerializer(typeof(Job));
        Job job = new Job
        {
            refno = "XXX",
            specialisms = new SpecialismList { 1, 2 }
        };
        XmlWriterSettings ws = new XmlWriterSettings
        {
            OmitXmlDeclaration = true,
            Indent = true,
            IndentChars = "  ",
            Encoding = new UTF8Encoding(false),
        };
        XmlWriter w = XmlWriter.Create(ms, ws);
        dcs.WriteObject(w, job);
        w.Flush();
        Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消