-1

我有一个如下的数据合同:

[DataContract]
class Person
{
    private string m_name;
    [DataMember]
    public string Name
     { get {return m_name;}
       set {m_name = value;}
     }
}

当 xml 序列化程序序列化此对象时,它会生成带有私有成员的 xml,例如

<person><m_name>john</m_name></person>

如何强制序列化程序仅序列化公共属性。

提前致谢。

4

2 回答 2

2

您的私人成员写入 xml 很奇怪。我试图模仿你的情况,序列化程序只写了公共字段:

    [数据合约]
    公共类人
    {
        私有字符串 m_name;
        [数据成员]
        公共字符串名称
        {
            得到 { 返回 m_name; }
            设置 { m_name = 值;}
        }
    }

private void Form1_Load(object sender, EventArgs e) { var person = new Person() {Name = "john"}; var xs = new XmlSerializer(typeof(Person)); var sw = new StreamWriter(@"c:\person.xml"); xs.Serialize(sw, person); }

您还可以阅读:http: //msdn.microsoft.com/en-us/library/83y7df3e%28VS.71%29.aspx

于 2013-03-28T02:55:21.910 回答
1

I did something similar to Andark's answer, except I used the DataContractSerializer instead of XmlSerializer. This was done in VS 2012 targeting .NET 4.5.

Here's the test code:

using Sytem;
using System.IO;
using System.Runtime.Serialization;

namespace ConsoleApplication1
{

    class Program
    {

        static void Main(string[] args)
        {

            Person myPerson = new Person() { Name = "Tim" };

            using (FileStream writer = new FileStream("Person.xml", FileMode.Create, FileAccess.Write))
            {

                DataContractSerializer dcs = new DataContractSerializer(typeof(Person));
                dcs.WriteObject(writer, myPerson);
            }
        }
    }

    [DataContract]
    class Person
    {

        private string m_name;

        public string Name
        {
            get
            {
                return m_name;
            }
            set
            {
                m_name = value;
            }
        }
    }
}

When I run this, I get the following XML:

<Person xmlns="http://schemas.datacontract.org/2004/07/ConsoleApplication1"
        xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Name>Tim</Name>
<Person>

Which is what is expected.

It's important to note that the default serializer for DataContract is the DataContractSerializer, not XmlSerializer, and there are some differences. Only members that are marked with [DataMember] should be serialized, and the access level (private, public, etc) is irrelevant - if you mark a private field or member with [DataMember], it will be serialized.

于 2013-03-28T06:33:21.410 回答