views:

46

answers:

2

I have customizable object class I'd like to serialize:

public partial class CustomObject
{               
    public List<CustomProperty> Properties;
}

public class CustomProperty
{              
    public object Value;                
    [XmlAttribute]
    public string Name;
}

// some class to be used as a value for CustomProperty
public class Person
{
  public string Name;
  public string Surname;
  public string Photo;
  [XmlAttribute]
  public int Age;
}

Currently XML serialization output looks like this:

<CustomObject>
  <Properties>
    <CustomProperty Name="Employer">
      <Value p6:type="Person" xmlns:p6="http://www.w3.org/2001/XMLSchema-instance" Age="30">
        <Name>John</Name>
        <Surname>Doe</Surname>
        <Photo>photos/John.jpg</Photo>
      </Value>
    </CustomProperty>
    <CustomProperty Name="Desc">
      <Value xmlns:q1="http://www.w3.org/2001/XMLSchema" p7:type="q1:string" xmlns:p7="http://www.w3.org/2001/XMLSchema-instance"&gt;some text</Value>
    </CustomProperty>
  </Properties>
</CustomObject>

First and foremost I'd like to remove namespaces and all that noise.

The end result should look like this:

<CustomObject>
  <Properties>
    <CustomProperty Name="Employer">
      <Person Age="30">
        <Name>John</Name>
        <Surname>Doe</Surname>
        <Photo>photos/John.jpg</Photo>
      </Person>
    </CustomProperty>
    <CustomProperty Name="Desc">
      <string>some text</string>
    </CustomProperty>
  </Properties>
</CustomObject>

Or this:

<CustomObject>
  <Properties>
    <Person Name="Employer" Age="30">
      <Name>John</Name>
      <Surname>Doe</Surname>
      <Photo>photos/John.jpg</Photo>
    </Person>
    <string Name="Desc">
      some text
    </string>
  </Properties>
</CustomObject>

How can make XmlSerializer to output it like that?

+1  A: 

Look at XmlElement attribute - this may solve your problem at least partially. From MSDN:

public class Things {
    [XmlElement(DataType = typeof(string)),
    XmlElement(DataType = typeof(int))]
    public object[] StringsAndInts;
 }

will produce

 <Things>
    <string>Hello</string>
    <int>999</int>
    <string>World</string>
 </Things>
VinayC
It looks like MSDN actually has an error in the example,I think it should be [XmlElement(Type = typeof(string))][XmlElement(Type = typeof(int))], because DataType is string. But this works too! Thanks!
JBeurer
+1  A: 

You can also specify the element name to make sure that the types are correctly processed:

[System.Xml.Serialization.XmlElementAttribute("files", typeof(Files))]
[System.Xml.Serialization.XmlElementAttribute("metrics", typeof(Metrics))]
public object[] Items { get; set; }
Johann Blais
This gets the first desired case. Thanks!
JBeurer