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
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;
Getting XPath expression for an XMLNode
MLangille
JReuben1
Manes
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] + ":" + basenames
}
You can of course alias the namespace to get shorter paths. This is left as an exercise for the reader.
Hope it helps,
Misha