Search code examples
c#xamlworkflow-foundation-4

Find and replace in XAML programatically


I'm trying to programatically parse/search a XAML file for a certain node then a certain attribute to modify it. The XAML is a windows workflow so its not really user controls. I have found many examples using XamlReader to parse a Xaml file to look for controls and then modify the controls. But in my case I'm looking for custom activities which are not dependancyObjects. Can I use XamlReader to find custom activities in a windows workflow Xaml and modify certain attributes? Or is there a better solution?


Solution

  • You don't need to use XamlReader, use XmlDocument and walk through the elements and attributes.

    Here's what we do, just write the "DoYourStringReplace" method:

    private void ParseXml(
        TextWriter resultStream,
        TextReader sourceStream)
    {
        XmlDocument doc = new XmlDocument();
        doc.PreserveWhitespace = true;
        doc.Load(sourceStream);
        ParseXmlNodes(doc.DocumentElement);
    
        using (XmlWriter xw = XmlWriter.Create(resultStream))
        {
            doc.WriteTo(xw);
        }
    }
    
    /// <summary>
    /// Parse a single XML node and its children.
    /// </summary>
    /// <param name="node"></param>
    private void ParseXmlNodes(XmlNode node)
    {
        if (node.NodeType == XmlNodeType.Element)
        {
            //
            //  Replace tokens in XML attribute values
            //
            foreach (XmlAttribute a in node.Attributes)
            {
                a.Value = DoYourStringReplace(a.Value);
            }
        }
        else if (node.NodeType == XmlNodeType.Text)
        {
            //
            //  Replace tokens in the XML Element value
            //
            node.Value = DoYourStringReplace(node.Value);
        }
    
        //
        //  Do the same thing for all children
        //
        foreach (XmlNode child in node.ChildNodes)
        {
            ParseXmlNodes(child);
        }
    }