I wan开发者_如何学运维t to generate a serialization assembly or .cs file to serialize my types using XmlAttributeOverrides, and then reference this assembly/.cs file in my project directly rather than use XmlSerializer to perform xml serialization/deserialization. This is because the serialization uses XmlAttributeOverrides and when you create an XmlSerializer with overrides it doesn't look for an existing assembly but will always re-generate one (reference). My program runs in an environment where it's not possible to run csc.exe, therefore my I cannot generate a serialization assembly at runtime.
To be clear, I can't just use sgen.exe because that only generates assemblies that perform the default xml serialization/deserialization. If you create an XmlSerializer and pass it XmlAttributeOverrides in the constructor then Serialize() and Deserialize() do NOT use the assembly generated by sgen.exe, therefore sgen.exe seems of no use to me. When using overrides XmlSerializer will always generate a new assembly.
So, is there a way I can call XmlSerializer or other classes and get it to create a .cs file or dll that I can include in my project? I'd like to automate this process if possible so I don't need to make manual changes whenever I change my types that are being serialized. I can't use sgen.exe /k because that only generates the default XmlSerializer for a type instead of the one I need which uses overrides. Is there another way to generate or capture the .cs file that's created by XmlSerializer?
(I have a related question here that's the root of this one)
You can generate the assemblies at compile time. In Visual Studio open project properties
, click the build
tab and scroll down to Generate serialization assemblies
.
Setting this to on
will compile them locally so that they may be deployed with your solution. They can also be compiled using the Sgen.exe
tool. See here for more info.
Generate serialization assembly
Specifies whether the compiler will use the XML Serializer Generator Tool (Sgen.exe) to create XML serialization assemblies. Serialization assemblies can improve the startup performance of XmlSerializer if you have used that class to serialize types in your code. By default, this option is set to Auto, which specifies that serialization assemblies be generated only if you have used XmlSerializer to encode types in your code to XML. Off specifies that serialization assemblies never be generated, regardless of whether your code uses XmlSerializer. On specifies that serialization assemblies always be generated. Serialization assemblies are named TypeName.XmlSerializers.dll. For more information, see XML Serializer Generator Tool (Sgen.exe).
From the last comment I see your issue. Refer to this question, I believe if your using XmlAttributeOverrides
the assembly will always be generated.
Hence if you can't launch csc.exe then don't use XmlAttributeOverrides
.
精彩评论