mganss / XmlSchemaClassGenerator

Generate C# classes from XML Schema files
Apache License 2.0
589 stars 179 forks source link

Property with name "System" conflicts with the usage of the System namespace #481

Closed Archomeda closed 7 months ago

Archomeda commented 7 months ago

Given the following schema: eExact-XML.zip

When I try to generate the files with the following command: XmlSchemaClassGenerator.Console -p Schemas --sf --nc --nr -o out eExact-XML.xsd

It generates two files that will not compile: GlTransactionLineIntraStat.cs and TypeAccountIntraStat.cs. As example, in the TypeAccountIntraStat.cs, the following code is invalid:

[System.Diagnostics.CodeAnalysis.AllowNullAttribute()]
[System.Diagnostics.CodeAnalysis.MaybeNullAttribute()]
[System.Xml.Serialization.XmlElementAttribute("System", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public object System { get; set; }

The error is on the Form=System.Xml.Schema.XmlSchemaForm.Unqualified part. The namespace System cannot be referenced because a property of the same name exists in this class.

As a workaround, I can use the --cn flag on this file, so that it drops the namespace part, and uses the enum class directly via the usings.

mganss commented 7 months ago

You should also be able to use the --codeTypeReferenceOptions=GlobalReference command line option to make the generated code use the global namespace alias global::.

Another option would be to create a different property name by using the command line option --tns.

Archomeda commented 7 months ago

Why not change it so that the global namespace is used by default? Seems to me that generating code that compiles without having to dive into the arguments would be the best.

mganss commented 7 months ago

This issue seems to be a corner case that wouldn't justify cluttering the generated code with global:: for the vast majority of cases. So I'd prefer to leave it like it this for now.

I was thinking of perhaps adding code to detect cases where it would be necessary to add the global namespace alias. I'm not sure but wouldn't that be only ever necessary if there's a property named System?

Another option would be to never allow a property named System and instead use a (configurable) replacement name like SystemProperty.