How to customize XML serialization output for Object?
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">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?
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; }
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>
you can remove namespace like
StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb);
XmlSerializer serializer = new XmlSerializer(typeof(WSOpenShipments), myns);
var ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, "");
serializer.Serialize(writer, OS, ns);
xmlString = sb.ToString();
usse this -- ns.Add(string.Empty, "");
精彩评论