tags:

views:

57

answers:

1

I have an XML Template file. This file contains a header and some predefined element Sections.

eg:

 <?xml version="1.0" encoding="utf-8"?>
 <Sections>      
  <Section PageSize="Letter"  PageMargins="35" PagePaddings="5">                   
    <Header Height="130" Repeat="False" >               
      <Image Source="Resources/logo1.bmp" Left="30" Top="34" Width="65" KeepRatio="True" />
      <Text Left="75" Top="34" Width="510" Alignment="Center"  Style="TitleTextStyleBold">$Title$</Text>      
      <Image Source="Resources/logo2.bmp" Left="500" Top="34" Width="65" KeepRatio="True" />   
    </Header>
   </Section>
 </Sections>

I want to dynamically create some element groups in XML format (as string).

eg:

   <Group Layout="Horizontal" Margins="0, 13">
        <Text Margins="0, 0, 0, 0" Width="180" Alignment="Center"  Style="TextStyleBold">DataItem Name</Text>   
        <Text Margins="0, 0, 0, 0" Width="180"  Alignment="Center" Style="TextStyleBold">DataItem Value</Text>      
        <Text Margins="0, 0, 0, 0" Width="180" Alignment="Center"  Style="TextStyleBold">DataItem Unit</Text>       
   </Group>

I want to dynamically append the above groups to the existing template XML file, using C#. The final appended XML should look like this:

eg:

 <?xml version="1.0" encoding="utf-8"?>
 <Sections>      
  <Section PageSize="Letter"  PageMargins="35" PagePaddings="5">                   
    <Header Height="130" Repeat="False" >               
      <Image Source="Resources/logo1.bmp" Left="30" Top="34" Width="65" KeepRatio="True" />
      <Text Left="75" Top="34" Width="510" Alignment="Center"  Style="TitleTextStyleBold">$Title$</Text>      
      <Image Source="Resources/logo2.bmp" Left="500" Top="34" Width="65" KeepRatio="True" />   
    </Header>
    <Group Layout="Horizontal" Margins="0, 13">
        <Text Margins="0, 0, 0, 0" Width="180" Alignment="Center"  Style="TextStyleBold">DataItem Name</Text>   
        <Text Margins="0, 0, 0, 0" Width="180"  Alignment="Center" Style="TextStyleBold">DataItem Value</Text>      
        <Text Margins="0, 0, 0, 0" Width="180" Alignment="Center"  Style="TextStyleBold">DataItem Unit</Text>       
   </Group>
   </Section>
 </Sections>

How do I append string(XML Format) content to XML template content in C#?

+2  A: 

You can use an instance of XDocument to represent your existing XML and XElement to represent the content you wish to add.

These are in the System.Xml.Linq namespace, part of .NET 3.5+

Here's an example. For the purposes of this example, I have the main XML in a string called xml, the new section of XML in a string called xmlToAdd.

    XDocument document = XDocument.Parse(xml);
    XElement element = XElement.Parse(xmlToAdd);

    document.Root.Element("Section").Add(element);
Anthony Pegram