0

I've got a class that includes an XElement object...

public class SomeClass
{
    public string prop1 = "";
    public string prop2 = "";
    public XElement elem = null;
}

I'm setting the XElement property later in the code with an instance of another internally defined class object...

UserFields userFields = new UserFields();
SomeClass sc = new SomeClass();
sc.prop1 = "Sam";
sc.prop2 = "Smith";
sc.elem = new XElement("UserFields", userFields);

The problem is that when I use XmlSerializer to serialize the class objects to XML, I'm only getting the fully qualified class name for the SomeClass.elem property...

StringWriter sw = new StringWriter();
XmlSerializer x = new XmlSerializer(o.GetType());
x.Serialize(sw, o);
string xmlString = sw.ToString();

I get this as output...

<SomeClass>
    <prop1>Sam</prop1>
    <prop2>Smith</prop2>
    <elem>MyNamespace.UserFields</elem>
</SomeClass>

It seems like the XmlSerializer doesn't know quite what to do with the XElement object. I'd like to find a way to get the XML out of the XElement object serialized as an XML string like is happening with the other class object. Any ideas?

  • 1
    Does applying a `[XmlAnyElement]` tag to the `elem` property, produce the desired output? – Xiaoy312 Mar 22 '17 at 20:59
  • [`[XmlAnyElement]`](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlanyelementattribute.aspx) will do the job, see for instance [this answer](http://stackoverflow.com/a/30278016/3744182). – dbc Mar 22 '17 at 23:04

1 Answers1

0

Ok I've found my answer. The problem was not in the serialization, but in the class object's assignment to the XElement. Since the class object was a normal run-of-the-mill class like you would define in any C# project, the assignment to the XElement was calling the object's ToString() method which returns the fully qualified class name (which is what was appearing after the object was serialized to XML). XElement needs to be assigned either simple types or other X-types. In my case, the following accomplished adding all of the class' properties to the XElement and the later serialization worked as expected. The [XmlAnyElement] attribute wasn't necessary.

List<XElement> items = new List<XElement>();
FieldInfo[] fields = typeof(UserFields).GetFields();
foreach (FieldInfo fld in fields)
    items.Add(new XElement(fld.Name, fld.GetValue(userFields.Content)));
sc.elem = new XElement("UserFields", items);

This returns something like the following...

<Root>
    <SomeField>the value</SomeField>
    ...
    <UserFields>  <-- this section is what is generated from the list of XElement objects
        <UserField1>value1</UserField1>
        ...
        <UserFieldN>valueN</UserFieldN>
    </UserFields>
</Root>