省略 XmlSerializer.Serialize 上的节点
我有一个第三方提供的类库,其中有一个名为 SaveAccount 的类型。当我尝试序列化此类时,我得到以下 xml:
<?xml version="1.0" encoding="utf-16"?>
<SaveAccount xmlns="http://RiskBrowser/ExposureManager">
<Body>
<Token>JHSDUKJSHDKJ</Token>
<JobId>2</JobId>
</Body>
</SaveAccount>
我需要做的是仅删除 标签,所以我最终会得到以下结果:
<?xml version="1.0" encoding="utf-16"?>
<SaveAccount xmlns="http://RiskBrowser/ExposureManager">
<Token>JHSDUKJSHDKJ</Token>
<JobId>2</JobId>
</SaveAccount>
有没有一种好的方法可以做到这一点在 XmlSerializer 内部?或者有人能想到的另一种好方法?我真的不想开始修改生成的 xml。
预先非常感谢
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" encoding="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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果
Body
是公共属性(即SaveAccount
不是IXmlSerialized
),并且SaveAccount
中没有其他属性可用于序列化后,您可以通过直接序列化Body
并应用 XML 序列化程序属性覆盖来重命名并将正确的命名空间分配给结果元素来删除此节点。否则,您可以创建自定义 XmlWriter 并在写入时抑制此节点。If
Body
is a public property (i.e.SaveAccount
is notIXmlSerializable
) and there are no other properties inSaveAccount
to serialize, you can remove this node by serializingBody
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.在这种情况下,一种方法是在生成
XML
后使用LINQ to XML
或 <代码>System.Xml。In this situation, one way would be manipulating the
XML
after it has been generated to remove theBody
node from it usingLINQ to XML
orSystem.Xml
.使用 XmlIgnore 属性标记类型,如下所示:
如果无法重建第三方库,则可以使用 XmlAttributeOverrides 类来覆盖序列化对象的默认方式,类似于:
Mark the type with the XmlIgnore attribute, like so:
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: