簡體   English   中英

我如何使用System.Xml.Serialization注釋此.net類型以序列化/反序列化以下XML /從以下XML

[英]How would I annotate this .net Type to serialise/deserialise to/from the following XML, using System.Xml.Serialization

方式:

public class Foo
{
    public string Bar { get; set; }
    public string Fred { get; set; }
}

實例

Foo x = new Foo { Bar = "Hi", Fred = "hey yourself" };

XML:

<Foo>
   <Bar>Hi</Bar>
   <John>                         <!-- Note extra layer -->
       <Fred>hey there</Fred>
   </John>
</Foo>

注意額外的John標記,但沒有為John創建特殊類型。 如果我不能注釋它,該如何以編程方式控制序列化過程。

嘗試這個 :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Runtime;
using System.Runtime.InteropServices;

namespace ConsoleApplication42
{
    class Program
    {

        static void Main(string[] args)
        {

            Foo x = new Foo { Bar = "Hi", Fred = "hey yourself" };
            //<Foo>
            //   <Bar>Hi</Bar>
            //   <John>                         <!-- Note extra layer -->
            //       <Fred>hey there</Fred>
            //   </John>
            //</Foo>

            XElement foo = new XElement("Foo", new object[] {
                new XElement("Bar", x.Bar),
                new XElement("John", new XElement("Fred", x.Fred))
            });

        }
    }
    public class Foo
    {
        public string Bar { get; set; }
        public string Fred { get; set; }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM