简体   繁体   English

如何仅序列化所选属性

[英]How to serialize selected properties only

I have one class Person and it has some public properties . 我有一类人,它有一些公共属性。 Now I want to serialize person class but with some selected properties only . 现在,我要序列化人类, 但仅具有某些选定的属性 This can be achieve by making that property private but I don't want to change any property as private. 可以通过将该属性设置为私有来实现,但是我不想将任何属性更改为私有。

If its not possible using serialisation then, what is another way to create xml doc for object with selected properties only. 如果无法使用序列化,那么为仅具有选定属性的对象创建xml文档的另一种方法是。

Note: All properties must be public. 注意:所有属性必须是公共的。

  class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person();
            using (MemoryStream memoryStream = new MemoryStream())
            {
                XmlSerializer xmlSerializer = new XmlSerializer(person.GetType());
                xmlSerializer.Serialize(memoryStream, person);
                using (FileStream fileStream = File.Create("C://Output.xml"))
                {
                    memoryStream.WriteTo(fileStream);
                    fileStream.Close();
                }
                memoryStream.Close();
            }
        }
    }

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public double Salary { get; set; }

        public Person()
        {
            Id = 1;
            Name = "Sam";
            Salary = 50000.00;
        }
    }

Current Output 电流输出

  <?xml version="1.0"?>
  <Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Id>1</Id>
    <Name>Sam</Name>
    <Salary>50000</Salary>
  </Person>

Expected Output 预期产量

  <?xml version="1.0"?>
  <Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">   
    <Salary>50000</Salary>
  </Person>

You could use an XmlIgnore attribute.. 您可以使用XmlIgnore属性。

 public class Person
    {
        [XmlIgnore]
        public int Id { get; set; }
        [XmlIgnore]
        public string Name { get; set; }
        public double Salary { get; set; }

        public Person()
        {
            Id = 1;
            Name = "Sam";
            Salary = 50000.00;
        }
    }

See this 看到这个

can you give a try to below code and just use XmlIgnore attribute on he properties which you not require :- 您可以尝试下面的代码,并在不需要的属性上使用XmlIgnore属性吗:-

    [XmlIgnore]
    public int Id { get; set; }

    [XmlIgnore]
    public string Name { get; set; }

    public double Salary { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM