Editor for WinForms | ComponentOne
Creating an XHTML Editor in Code / Performing Other Common Tasks / Selecting a Paragraph using the XmlDocument
In This Topic
    Selecting a Paragraph using the XmlDocument
    In This Topic

    To perform the same task using the XmlDocument object model, you would use this code:

    To write code in C#

    C#
    Copy Code
    void selectXmlNode_Click(object sender, EventArgs e)
    {
        // find 6th node in document
        XmlDocument doc = c1Editor1.Document;
        XmlNodeList nodes = SelectNodes(doc, "/html/body/p");
        if (nodes.Count > 5)
        {
            XmlNode node = nodes[5];
            C1TextRange range = c1Editor1.CreateRange();
            range.MoveTo(node);
            range.Select();
        }
    }
    

    The code is considerably simpler. It retrieves the current document from the C1Editor, and then uses the SelectNodes helper method to get a list of all paragraph tags. It then creates a C1TextRange object, moves this new range to the node that represents the sixth paragraph in the document, and selects the range using the C1TextRange's Select method.

    The SelectNodes method is a handy utility that takes care of XML namespaces by automatically creating and using an XmlNamespaceManager (this is standard XmlDocument logic, not directly related to the C1Editor):

    To write code in C#

    C#
    Copy Code
    XmlNodeList SelectNodes(XmlDocument doc, string xpath)
    {
        if (doc.DocumentElement.Attributes["xmlns"] != null)
        {
            // add namespace manager
            string xmlns = doc.DocumentElement.Attributes["xmlns"].Value;
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
            nsmgr.AddNamespace("x", xmlns);
            xpath = xpath.Replace("/", "/x:");
            return doc.SelectNodes(xpath, nsmgr);
        }
        else
        {
            return doc.SelectNodes(xpath);
        }
    }