开发者

Custom XML Serialization, how to write custom root element?

I'm probably just doing this wrong, i know.

I'm using custom serialization and when the xml is generated it's putting the class name as the root element

Example:

<MyClassName>
 <MyIntendedRootNode>
   <ObjectType>
     <Property1/>
     <Property2/>
...

I'm invoking the serialization by calling xmlserializer.Serialize(writer,Me) so I'm sure that has something to do with it.

I've tried putting XMLRoot onto the class, but I think as vb is compiling this partial class with its aspx page, it's either overwriting this property or ignoring it entirely.

Ideally I'd like to just tell it to eit开发者_运维技巧her throw away everything it has and use a different root element.

Anybody else do this except me?

Thanks


You can use either IXmlSerializable or use the XML attributes. I use XmlSerializer passing the root in the constructor.

var MemoryStream ms;
var customRoot = dataObject as XmlRootAttribute;
var xml = new XmlSerializer(dataObject.GetType(), customRoot);
xml.Serialize(ms, dataObject);


In ASP.NET, the actual class that is loaded is a generated class that inherits from your class. (It turns out--surprisingly--that this generated code is actually separate from the additional generated code that is combined with your code using the partial class technique. The generated class has the same name as the class you are working on, but it is in a different namespace.) Since XmlRoot is not an inherited attribute, the XmlSerializer does not see it.

I don't think there is any solution (other than modify the document after you have generated it).


Are you trying to serialize a codebehind file?

I would suggest writing a model to contain the data that needs to be saved, and then serializing that instead. Then use the appropriate XMLWriter attributes to make sure your root element is correctly named.


Or you could implement IXmlSerializable and have full control over your Xml but its a bit of extra effort just to change a root element name.


You can create a wrapper class and give that wrapper class with the name that you wish to be shown in the xml root.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜