vba - How to detect the namespaces in a foreign XML document using MSXML2? -


when working xml using msxml2, it's pretty documented xpath queries work, need define selectionnamespaces property. however, straightforward fix if know namespaces are. i'm writing module in vba hope able use parse office xml formats, , i'd function can arbitrarily define namespaces documents load them.

at present, i've found following isn't bad first stab:

public dodefinenamespaces(strrootnodename string, strfilepath string, byref omydoc msxml2.domdocument60)     dim orootnode msxml2.ixmldomnode     dim omydoc msxml2.domdocument60     dim oattribute msxml2.ixmldomnode     sim strnamespaces string      set omydoc = new msxml2.domdocument60     omydoc.load strfilepath     set orootnode = omydoc.selectnodes("./*[name()='" & strrootnodename & "']")     each oattribute in orootnode.attributes         if oattribute.namespace = "http://www.w3.org/2000/xmlns/"              strnamespaces = strnamespaces & oattribute.xml         end if     next oattribute     omydoc.setproperty("selectionnamespaces", strnamespaces) end sub 

with couple of subtle changes dealing default namespace. however, won't work fell xml following:

<?xml> <root xmlns:t="myfirstns">    <t:object1>        <r:object2 xmlns:r="mysecondns" />    </t:object1> </root> </xml> 

aside traversing, there approach might better mine dealing kind issue = i.e. namespace not defined in root node? ideal xpath 1.0 expression select xmlns attribute nodes when namespace exist in has yet added selectionnamespaces, or building xslt transform produce nodeset namespaces of document.

to determine namespaces used in document, use xpath 1.0 query:

/*/namespace::* 

this include duplicates.

for xpath 2.0, you'd go for

distinct-values(//*/fn:namespace-uri()) 

instead namespace axis deprecated. both return namespaces in use (and omits ones not used). query removes duplicate namespaces.

anyway: if don't care namespaces, might more reasonable ignore them. in xpath 1.0 have use wildcard axis step , name test in predicate. match elements <foo/> arbitrary namespaces, use //*[local-name() = 'foo'] respectively //*:foo in xpath 2.0.


Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -