问题
I've got a tough problem. Let's say I have a class named ObjectHost
, containing a property of type BusinessObject
, which itself contains some properties (let's say a Name
and a Town
as strings).
The code would be :
public class ObjectHost
{
public BusinessObject Data { get; set; }
public ObjectHost()
{
Data = null;
}
public ObjectHost(BusinessObject ei)
{
Data = ei;
}
public override string ToString()
{
return (Data == null) ? "null" : Data.ToString();
}
}
When serializing, it will produce something like :
<ObjectHost>
<Data>
<Name>My name</Name>
<Town>London</Town>
</Data>
</ObjectHost>
Where I'd like it to be :
<Name>My name</Name>
<Town>London</Town>
as it is only an encapsulation object in my particular use (for some other purposes).
I tried using XmlRoot
and XmlElement
attributes but I didn't achieve my goal.
Is there a solution for this ?
回答1:
As I have understood, you are using XmlSerializer to serialize an Object.
You are passing in ObjectHost and want only properties of ObjectHost.BusinessObject to be emitted.
You can use one of the following approaches
Post processing of serialized data -> use XPath queries to get desired data
/ObjectHost/Data
Customize serialize process: (This is little tricky)
a) Implement IXmlSerializable
b) Customize ReadXml, WriteXml, and GetSchemaIn the WriteXml, use XPath query, or other Xml methods (to get XmlNodes) and write only desired properties.
This approach will be tied to particular data structure, and cannot be used for incompatible data structure.
来源:https://stackoverflow.com/questions/10723302/how-to-serialize-an-included-object-property-as-a-root