How to get all metadata keys for any ItemGroup element?

Is there a way to get all the metadata keys associated with this element?

I want to do something like the following.

Given:

<ItemGroup> <MyItems Include="item1"> <key1>val1</key1> <key2>val2</key2> <key3>val3</key3> </MyItems> <MyItems Include="item2"> <key4>val4</key4> </MyItems> </ItemGroup> 

To be able to determine that item1 has metadata available for key1, key2 and key3, and that item2 has metadata available for key4, not knowing what the names of these keys really are.

In fact, I'm trying to use metadata to indicate attributes that I have no idea about, and then try to figure out a validation method to determine which attributes were specified.

In other words, I believe that the metadata of each element is just a hash containing key / value pairs, and I'm trying to figure out what all the keys are.

Does anyone know how to do this with msbuild?

thanks

+6
source share
1 answer

I decided to solve this problem with a custom built-in task like the following:

 <UsingTask TaskName="GetMetadataTask" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll" > <ParameterGroup> <MyItemGroup ParameterType="Microsoft.Build.Framework.ITaskItem[]" Required="true" /> <MetadataString Output="true" /> </ParameterGroup> <Task> <Using Namespace="System"/> <Code Type="Fragment" Language="cs"> <![CDATA[ StringBuilder command = new StringBuilder(); foreach (ITaskItem item in MyItemGroup ) { command.AppendFormat("ItemName={0}\r\n", item); foreach (string parameter in item.MetadataNames) { command.AppendFormat(" {0}={1}\r\n", parameter, item.GetMetadata(parameter)); } command.AppendFormat("\r\n"); } MetadataString = command.ToString(); ]]> </Code> </Task> </UsingTask> 

Note that the above will also include all the default metadata that MSBuild automatically adds to each item in the item group (for example, FullPath, RootDir, Filename, etc.). In my implementation, I added an extra check to ignore those metadata elements that I didn't like

Sample Usage:

 <GetMetadataTask MyItemGroup="@(YourItemGroup)"> <Output TaskParameter="MetadataString" PropertyName="YourMetadataString"/> </GetMetadataTask> <Message Text="$(YourMetadataString)" /> 

To see the message output in the Visual Studio output window, you may need to change the output volume of MSBuild to at least Normal.

+14
source

Source: https://habr.com/ru/post/948667/


All Articles