T4 Template containing XML results in parse errors

2019-05-12 03:44发布

I have created T4 Templates for the config files of my web and windows projects. I can successfully generate master web.config, and all configs for other environments, i.e. web.ci.config, etc..However, I could not get rid of the errors on my master tt files, such as :

  • Character '#', hexadecimal value 0x23 is illegal in an XML name.
  • Character '<', hexadecimal value 0x3c is illegal in XML attribute values.
  • Unexpected XML declaration. The XML declaration must be the first node in the document and no white space characters are allowed to appear before it.

I should be missing a xml schema or a reference, but what?


My file looks like:

<#@ template debug="true" hostSpecific="true" #>
<#@ output extension= ".config" #>  
<?xml version="1.0" encoding="utf-8"?>
<configuration>
...  
    <add key="FileUploadFolder" value="<#= this.FileUpload #>" /> 
...
</configuration>
<#+ 
   string FileUpload="\\\\server\\folder";
#>

And here is screenshot

2条回答
2楼-- · 2019-05-12 04:23

Same problem here. I worked around it by replacing in the .tt file the line

<?xml version="1.0" encoding="utf-8"?>

with

<# WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); #>

Once VS is confused about the XML format of the template file, it seems to persist in that confusion -- even after editing like above and a restart. The only way around that seems to be to delete the existing .tt file from your project and re-create it from scratch.

With this change, the .tt file does not have a <?xml?> tag anymore so VS does not consider it an XML file. It ignores everything inside the literal string. Your whole template now looks like this:

<#@ template debug="true" hostSpecific="true" #>
<#@ output extension= ".config" #>  
<# WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); #>
<configuration>
...  
    <add key="FileUploadFolder" value="<#= this.FileUpload #>" /> 
...
</configuration>
<#+ 
    string FileUpload="\\\\server\\folder";
#>
查看更多
对你真心纯属浪费
3楼-- · 2019-05-12 04:24

What's happening here is that the Xml language service in VS is mistakenly identifying your T4 file as an Xml file, so spewing lots of false positive error messages.

I'm looking into whether there's a workaround to force it to ignore T4 files. If you could log a bug on Microsoft Connect, that would be helpful.

查看更多
登录 后发表回答