我有我需要做一些自定义XML输出的类,所以我实现IXmlSerializable接口。然而,一些我想与默认的序列化输出的领域,除了我想改变的XML标记名称。当我打电话serializer.Serialize,我得到了默认的XML标记名称。我可以改变这些以某种方式?
下面是我的code:
公共类MyClass的:的IXmlSerializable
{
//这里的一些领域,我做自定义序列化的
...
//这些字段我想默认的序列化的,除了标签名称
公共字符串[] BatchId {获得;组; }
...
...的ReadXml和的getSchema方法是这里...
公共无效中WriteXML(XmlWriter的作家)
{
XmlSerializer的序列化=新的XmlSerializer(typeof运算(字符串[]));
serializer.Serialize(作家,BatchId);
...适用于其他领域...
//此方法做我的自定义XML的东西
writeCustomXml(作家);
}
//我的自定义XML的方法是在这里,工作正常
...
}
下面是我的XML输出:
< MyClass的>
< ArrayOfString>
<字符串> 2643-15-17< /串>
<字符串> 2642-15-17< /串>
...
< / ArrayOfString>
...我的自定义XML是正确的..
< / MyClass的>
我想最终获得的是:
< MyClass的>
< BatchId>
< ID> 2643-15-17< / ID>
< ID> 2642-15-17< / ID>
...
< / BatchId>
...我的自定义XML是正确的..
< / MyClass的>
解决方案
在很多情况下,你可以使用的XmlSerializer
构造函数重载接受一个 XmlAttributeOverrides
来指定这些额外的名称信息(例如,通过一个新的 XmlRootAttribute
) - 但是,这并不对数组工作AFAIK。我想到了的String []
例如它会更简单,只是手动写。在大多数情况下,的IXmlSerializable
是一个很多额外的工作 - 我避免它尽可能的像这样的原因。对不起。
I have a class that I need to do some custom XML output from, thus I implement the IXmlSerializable interface. However, some of the fields I want to output with the default serialization except I want to change the xml tag names. When I call serializer.Serialize, I get default tag names in the XML. Can I change these somehow?
Here is my code:
public class myClass: IXmlSerializable
{
//Some fields here that I do the custom serializing on
...
// These fields I want the default serialization on except for tag names
public string[] BatchId { get; set; }
...
... ReadXml and GetSchema methods are here ...
public void WriteXml(XmlWriter writer)
{
XmlSerializer serializer = new XmlSerializer(typeof(string[]));
serializer.Serialize(writer, BatchId);
... same for the other fields ...
// This method does my custom xml stuff
writeCustomXml(writer);
}
// My custom xml method is here and works fine
...
}
Here is my Xml output:
<MyClass>
<ArrayOfString>
<string>2643-15-17</string>
<string>2642-15-17</string>
...
</ArrayOfString>
... My custom Xml that is correct ..
</MyClass>
What I want to end up with is:
<MyClass>
<BatchId>
<id>2643-15-17</id>
<id>2642-15-17</id>
...
</BatchId>
... My custom Xml that is correct ..
</MyClass>
解决方案
In many cases, you can use the XmlSerializer
constructor-overload that accepts a XmlAttributeOverrides
to specify this extra name information (for example, passing a new XmlRootAttribute
) - however, this doesn't work for arrays AFAIK. I expect for the string[]
example it would be simpler to just write it manually. In most cases, IXmlSerializable
is a lot of extra work - I avoid it as far as possible for reasons like this. Sorry.