开发者

Omit a node on XmlSerializer.Serialize

I have a class library provided by a third party, with a type in there called SaveAccount. When I try to serialize this class I get the following xml:

<?xml version="1.0" encoding="utf-16"?>
<SaveAccount xmlns="http://RiskBrowser/ExposureManager">
  <Body>
    <Token>JHSDUKJSHDKJ</Token>
    <JobId>2</JobId>
  </Body>
</SaveAccount>

What I need to do is strip out just the <Body> tags so I end up with this:

<?xml version="1.0" encod开发者_Go百科ing="utf-16"?>
<SaveAccount xmlns="http://RiskBrowser/ExposureManager">
  <Token>JHSDUKJSHDKJ</Token>
  <JobId>2</JobId>
</SaveAccount>

Is there a nice way of doing this inside the XmlSerializer? Or another nice way someone can think of? I don't really want to start hacking around with the generated xml.

Many thanks in advance


If Body is a public property (i.e. SaveAccount is not IXmlSerializable) and there are no other properties in SaveAccount to serialize, you can remove this node by serializing Body directly and applying XML serializer attribute overrides to rename and assign the correct namespace to the resulting element. Otherwise, you can create a custom XmlWriter and suppress this node on write.


In this situation, one way would be manipulating the XML after it has been generated to remove the Body node from it using LINQ to XML or System.Xml.


Mark the type with the XmlIgnore attribute, like so:

[XmlIgnore]
public AType Body;

If you can't rebuild the third party library, you can use the XmlAttributeOverrides class to override the default way of serializing objects, something similar to:

XmlAttributes ignore = new XmlAttributes() { XmlIgnore = true};
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof (AType), "Body", ignore);
XmlSerializer ser = new XmlSerializer(typeof(BType), overrides);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜