Getting XPath expression for an XMLNode

Is there an easy way to determine or get the applicable XPath expression from a Microsoft.Office.Interop.Word.XMLNode instance at runtime   Or do I have to navigate through the XMLNodes and build the XPath string myself

Answer this question

Getting XPath expression for an XMLNode

  • MLangille

    Do you have a sample of that code  It would save me some time.
  • JReuben1

    Yep, not built in support. We build XPath ourselves by navigating to the root element.

  • Manes

    I have some C++ code that we use in VSTO to build the XPath for XMLNode which validates against schema etc. It is not an exact sample code that you are looking for. I will do this one time to save you time but please understand that it is the last time I am doing this - I have work to do as well.

    The idea though is something like this:

    // built the list of namespaces and basenames from the leaf node
    // up the tree
    List<string> namespaces = new List<string>;
    List<string> basenames = new List<string>;
    while (xmlNode.Parent() != null)
    {
       string namespaceURI = xmlnode.NamespaceURI;
       string  baseName = xmlnode.BaseName;

       namespaces.Add(namespaceURI);
       basenames.Add(baseName);
    }

    // iterate the lists backwards and construct the XPath
    StringBuilder xpath = new StringBuilder;
    int idx = 0;
    int count = namespaces.Count();
    for(idx = count - 1 ; idx >= 0 ; idx--)
    {
        xpath.Append("/" + namespaces[idx] + ":" + basenamesIdea);
    }

    You can of course alias the namespace to get shorter paths. This is left as an exercise for the reader.

    Hope it helps,
    Misha


  • Getting XPath expression for an XMLNode