How to create a XML file with MSBuild?

11,088

Quick and dirty...

<Target Name="CreateXml">
  <ItemGroup>
    <TestAssembly Include="$(TestsAssembliesOutputDir)\Emidee.*.Tests.dll" />
    <Line Include="line01"><Text>&lt;xunit&gt;</Text></Line>
    <Line Include="line02"><Text>&lt;assemblies&gt;</Text></Line>
    <Line Include="line03"><Text>&lt;assembly filename=&quot;%(TestAssembly.Identity)&quot; shadow-copy=&quot;true&quot; /&gt;</Text></Line>
    <Line Include="line04"><Text>&lt;/assemblies&gt;</Text></Line>
    <Line Include="line05"><Text>&lt;/xunit&gt;</Text></Line>
    <LineText Include="%(Line.Text)" />
  </ItemGroup>
  <WriteLinesToFile
     File="out.xml"
     Lines="@(LineText)"
     Overwrite="true"
     />
</Target>

Left as an exercise for you

  • The initial < ? xml line
  • Indentation (hint use CDATA inside <`Text>)

You could also use the following in WriteLinesToFile and omit the synthesized @(LineText)

    Lines="@(Line->'%(Text)')"
Share:
11,088

Related videos on Youtube

Emidee
Author by

Emidee

French programmer working in Belgium ;)

Updated on April 10, 2022

Comments

  • Emidee
    Emidee about 2 years

    I'd like to create a XML file within a MSBuild task.

    I have a list of files:

    <CreateItem Include="$(TestsAssembliesOutputDir)\Emidee.*.Tests.dll">
      <Output ItemName="TestsAssemblies" TaskParameter="Include" />
    </CreateItem>
    

    I'd like to create a XML which would look like:

    <?xml version="1.0" encoding="utf-8"?>
    <xunit>
      <assemblies>
        <assembly filename="PATH OF FILE #1" shadow-copy="true" />
        <assembly filename="PATH OF FILE #2" shadow-copy="true" />
      </assemblies>
    </xunit>
    

    How can I achieve that?

    Thanks in advance

    Mike