4

I am carrying out Xml serrialization using XmlSerializer. I am carrying out serialization of ClassA, which contains property named MyProperty of type ClassB. I don't want a particular property of ClassB to be serialized.

I have to use XmlAttributeOverrides as the classes are in another library. If the property was in ClassA itself, it would have been straightforward.

XmlAttributeOverrides xmlOver = new XmlAttributeOverrides();
XmlAttributes xmlAttr = new XmlAttributes();
xmlAttr.XmlIgnore = true;
xmlOver.Add(typeof(ClassA), "MyProperty", xmlAttr);

XmlSerializer ser = new XmlSerializer(typeof(ClassA), xmlOver);

How to accomplish if the property is in ClassB and we need to serialize ClassA ?

2
  • I take it you don't want to always ignore the property in ClassB for other cases? Otherwise it's as simple as adorning ClassBy.PropertyToIgnore with [XmlIgnore]? Commented Jul 30, 2013 at 13:15
  • yes @ChrisSinclair, you are correct. Commented Jul 30, 2013 at 13:18

1 Answer 1

5

You almost got it, just update your overrides to point to ClassB instead of ClassA:

XmlAttributeOverrides xmlOver = new XmlAttributeOverrides();
XmlAttributes xmlAttr = new XmlAttributes();
xmlAttr.XmlIgnore = true;

//change this to point to ClassB's property to ignore
xmlOver.Add(typeof(ClassB), "ThePropertyNameToIgnore", xmlAttr);

XmlSerializer ser = new XmlSerializer(typeof(ClassA), xmlOver);

Quick test, given:

public class ClassA
{
    public ClassB MyProperty { get; set; }
}

public class ClassB
{
    public string ThePropertyNameToIgnore { get; set; }
    public string Prop2 { get; set; }
}

And exporting method:

public static string ToXml(object obj)
{
    XmlAttributeOverrides xmlOver = new XmlAttributeOverrides();
    XmlAttributes xmlAttr = new XmlAttributes();
    xmlAttr.XmlIgnore = true;
    xmlOver.Add(typeof(ClassB), "ThePropertyNameToIgnore", xmlAttr);


    XmlSerializer xs = new XmlSerializer(typeof(ClassA), xmlOver);
    using (MemoryStream stream = new MemoryStream())
    {
        xs.Serialize(stream, obj);
        return System.Text.Encoding.UTF8.GetString(stream.ToArray());
    }
}

Main method:

void Main()
{
    var classA = new ClassA {
        MyProperty = new ClassB {
            ThePropertyNameToIgnore = "Hello",
            Prop2 = "World!"
        }
    };

    Console.WriteLine(ToXml(classA));
}

Outputs this with "ThePropertyNameToIgnore" omitted:

<?xml version="1.0"?>
<ClassA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <MyProperty>
    <Prop2>World!</Prop2>
  </MyProperty>
</ClassA>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.