Using XmlAttributeOverrides to read a flattened XML arrays

V

VRSki

Is there any way to use XmlAttributeOverrides to read in an XML file where an
element contains multiple types of repeated peers, for instance:

<?xml version="1.0" encoding="utf-8"?>
<RootElement>
<ElementA Value="10"/>
<ElementA Value="20"/>
<ElementB Value="1"/>
<ElementB Value="2"/>
</RootElement>

I'd like to use System.Xml.Serialization namespace to define classes for
elements, and then to just read it in using XmlSerializer:

The question is what overrides should be to be able to read in the xml file
into the defined classes (see below).

SAMPLE:

XmlAttributeOverrides overrides = ????';///
XmlSerializer serializer = new XmlSerializer(typeof(RootElement), overrides);
RootElement root = serializer.Deserialize(stream) as RootElement;

[Serializable]
public class RootElement
{
public RootElement()
{
ElementAs = new List<ElementA>();
ElementBs = new List<ElementB>();
}

public List<ElementA> ElementAs {get;set;}
public List<ElementB> ElementAs {get;set;}
}

[Serializable]
public class ElementA
{
[XmlAttribute("Value")]
public string Value {get;set;}
}

[Serializable]
public class ElementB
{
[XmlAttribute("Value")]
public string Value {get;set;}
}


Thank you for any help/insight.

VR
 
V

VRSki

Ok. Got it...

XmlAttributeOverrides overrides = new XmlAttributeOverrides ();
XmlAttributes attrs = null;
XmlElementAttribute attr = null;

attrs = new XmlAttributes();
attr = new XmlElementAttribute();

attr.ElementName = "ElementA";
attr.Type = typeof(ElementA);

// Add the element to the collection of elements.
attrs.XmlElements.Add(attr);
overrides.Add(typeof(RootElement), "ElementAs", attrs);


attrs = new XmlAttributes();
attr = new XmlElementAttribute();

attr.ElementName = "ElementB";
attr.Type = typeof(ElementB);

attrs.XmlElements.Add(attr);
overrides.Add(typeof(RootElement), "ElementBs", attrs);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top