序列化为 XML 时忽略属性 [英] Ignore a property when serializing to XML

查看:33
本文介绍了序列化为 XML 时忽略属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类,里面有很多大类.

I have a base class that has MANY big classes inside it.

例如,让我们说 Person 类.在里面,有一个Payment类,里面有一个CreditCard类,等等......

For example, Let's say Person class. Inside it, there is a Payment Class, inside there is a CreditCard class, and so on...

我正在尝试序列化 Person 类,我想排除其中的某些类.

I am trying to serialize Person class, and I would like to exclude certain classes inside it.

在这个例子中,我试图序列化 Person 类并忽略整个支付类.这是我到目前为止所做的,但它不起作用.

In this example, I am trying to serialize Person class and ignore the ENTIRE payment class. This is what I did so far, but it's not working.

你们能帮我弄清楚如何实现这一目标吗?谢谢

Can you guys help me figure out how I can achieve this? Thanks

        XmlAttributes att = new XmlAttributes { XmlIgnore = true };
        XmlAttributeOverrides xOver = new XmlAttributeOverrides();
        xOver.Add(typeof(Payment), "Payment", att);
        SerializeContractsRequest(items, xOver);

public static string Serialize<T>(T clrObject, XmlAttributeOverrides xmlOverrides) where T : class, new()
{
    XmlSerializer xs = xmlOverrides == null ? new XmlSerializer(typeof(T)) : new XmlSerializer(typeof(T), xmlOverrides);
    string xml = string.Empty;

    //A string builder that will hold the converted business object as an xml string
    StringBuilder sb = new StringBuilder();

    //The stream that will write the serialized xml to the stringbuilder object
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Encoding = Encoding.UTF8;

    XmlWriter writer = XmlWriter.Create(sb, settings);

    xs.Serialize(writer, clrObject);

    xml = sb.ToString();

    return xml;
}

此外,我不允许触摸 Payment 类 XML 属性.例如,我不允许在 Payment 类上添加 [XmlIgnore].

Also, I am not allowed to touch the Payment Class XML Attribute. For example, I am not allowed to add [XmlIgnore] on Payment Class.

我只需要在一种方法上使用它,所以我想在那里应用覆盖.但是,仅供您参考,这是 Payment 类的内容:

I only need this on one method so that's where I would like to apply the override. However, just for your reference, this is what Payment class has:

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Name="Payment", Namespace="http://schemas.datacontract.org/2004/07/ServicesLayer")]
    [System.SerializableAttribute()]
public partial class Payment
{

}

推荐答案

当您指定覆盖时,您传入包含该属性的类型:

When you specify an override, you pass-in the type that contains the property :

using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Xml.Serialization;

namespace WpfApplication10
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var person = new Person
            {
                Payment = new Payment { Amount = 100 },
                Payments = new List<Payment>
                {
                    new Payment { Amount = 200 }, 
                    new Payment { Amount = 400 }
                }
            };

            var attributes = new XmlAttributes { XmlIgnore = true };

            var overrides = new XmlAttributeOverrides();
            overrides.Add(typeof(Person), "Payment", attributes);
            overrides.Add(typeof(Person), "Payments", attributes);

            var serializer = new XmlSerializer(typeof(Person), overrides);
            using (var stringWriter = new StringWriter())
            {
                serializer.Serialize(stringWriter, person);
                string s = stringWriter.ToString();
            }
        }
    }

    public class Person
    {
        public List<Payment> Payments { get; set; }
        public Payment Payment { get; set; }
        public int SomethingElse { get; set; }
    }

    public class Payment
    {
        public decimal Amount { get; set; }
    }
}

结果:

<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SomethingElse>0</SomethingElse>
</Person>

这篇关于序列化为 XML 时忽略属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆