Editor for WinForms | ComponentOne
Creating an XHTML Editor in Code / Performing Other Common Tasks / Search and Replace with the XmlDocument
In This Topic
    Search and Replace with the XmlDocument
    In This Topic

    To perform the same search/replace task with the XmlDocument object model, you would use the following code:

    To write code in C#

    C#
    Copy Code
    void replaceUsingXmlDocument(object sender, EventArgs e)
    {
        XmlDocument doc = this.c1Editor1.Document;
        XmlNodeList nodes = SelectNodes(doc, "/html/body");
        if (nodes.Count > 0)
        {
            ReplaceNodeText(nodes[0], "user", "customer");
        }
    }
    

    The code uses the SelectNodes method described earlier to select a single node that represents the document's body. It then calls the helper method ReplaceNodeText given below:

    To write code in C#

    C#
    Copy Code
    void ReplaceNodeText(XmlNode node, string search, string replace)
    {
        foreach (XmlNode child in node.ChildNodes)
        {
            ReplaceNodeText(child, search, replace);
        }
        if (node.NodeType == XmlNodeType.Text)
        {
            node.InnerText = node.InnerText.Replace(search, replace);
        }
    }
    

    ReplaceNodeText then takes an XmlNode as a parameter and scans all the node's children by calling itself recursively until it reaches a text node. At that point, it uses the regular string.Replace method to modify the content of the node.

    The changes made to the XmlDocument are automatically reflected in the C1Editor. Exposing the power and flexibility of the XmlDocument object model for processing XHTML documents is one of the main advantages of the C1Editor control.