Modifying the XAML file

I need to write a small console application that takes a XAML file as a parameter and then makes a copy of it with two modifications:

1) All attributes Text

are set to the "example" line (not for every tag, only where they were actually set to something else)

2) All tags containing the attribute Header

will instead have a header template inside the tag. For example, this:

<GridViewColumn Header="example">
    <!-- Some other stuff... -->
</GridViewColumn>

      

Should be changed to this:

<GridViewColumn>
    <GridViewColumn.HeaderTemplate>
       <DataTemplate>
           <TextBlock Text="example"/>
       </DataTemplate>
</GridViewColumn>

      

I was thinking about using Regex for logic, but I want to know if there is an easier way to do this?

+3


source to share


1 answer


Using correct XML parsing to modify XML will be more reliable because a decent XML parser will never generate well-formed XML , except regex is not an XML parsing tool .

Since you didn't start with or look like this with any XML parser, the following is just to illustrate how it can be done with an XML parser, LINQ-to-XML .

Consider the following XAML and a predefined data template:

var xaml = @"<StackPanel>
    <TextBlock Text='not example'/>
    <!-- Some other stuff... -->
    <GridViewColumn Header='example'>
        <!-- Some other stuff... -->
    </GridViewColumn>
</StackPanel>";
var templateXaml = @"<DataTemplate>
    <TextBlock Text='example'/>
</DataTemplate>";
var doc = XDocument.Parse(xaml); //or load from file: XDocument.Load("path-to-XAML.xaml");
var template = XElement.Parse(templateXaml);

      

To apply mod # 1, you can simply do the following:

foreach (var attr in doc.Descendants().Attributes("Text").Where(o => o.Value != "example"))
{
    attr.Value = "example";
}

      



and for modification No. 2:

foreach (var element in doc.Descendants().Where(o => o.Attribute("Header") != null))
{
    //delete all existing content
    element.DescendantNodes().Remove();
    //add new content element named "ParentElementName.HeaderTemplate"
    element.Add(new XElement(element.Name.LocalName + ".HeaderTemplate", template));
}
//print the modified XDocument (or save to file instead)
Console.WriteLine(doc.ToString());

      

- Dotnetfiddle

console output:

<StackPanel>
  <TextBlock Text="example" />
  <!-- Some other stuff... -->
  <GridViewColumn Header="example">
    <GridViewColumn.HeaderTemplate>
      <DataTemplate>
        <TextBlock Text="example" />
      </DataTemplate>
    </GridViewColumn.HeaderTemplate>
  </GridViewColumn>
</StackPanel>

      

+2


source







All Articles