Skip to content Skip to sidebar Skip to footer

Searching For Xpath Expression With Colon In Attribute Name Throws Exception (node.js Elementtree Module)

Using the elementtree package in nodejs, I'm trying to verify the existence of a certain xml attribute in an xml file (specifically an android manifest file). var manifestTxt = fs.

Solution 1:

In case you don't have the information how to register the namespace and use the associated prefix for it, use:

application/activity
   [@*[local-name()=name' 
     and 
      namespace-uri() = 'http://schemas.android.com/apk/res/android'
      ] 
   = 
    'com.whatever.app'
   ]

Simpler expressions that aren't safe in the general case, but may select the wanted node(s) in this specific case:

application/activity[@*[local-name()='name'] = 'com.whatever.app']

or this expression:

application/activity[@*[name()='android:name'] = 'com.whatever.app']

Solution 2:

Elementtree expects namespace URIs, not namespace prefixes.

var manifestTxt = fs.readFileSync('AndroidManifest.xml', 'utf-8'),
    manifestDoc = new et.ElementTree(et.XML(manifestTxt)),
    expected = '//application/activity[@{http://schemas.android.com/apk/res/android}name="com.whatever.app"]';

test.ok( manifestDoc.find(expected) );

See: ElementTree: Working with Qualified Names


Edit The XPath implementation of node-elementtree does not currently seem to have namespace support at all.

Missing that you'd have to do some legwork:

var manifestTxt = fs.readFileSync('AndroidManifest.xml', 'utf-8'),
    manifestDoc = new et.ElementTree(et.XML(manifestTxt)),
    activities = manifestDoc.findall('//application/activity'), i;

for (i=0; i<activities.length; i++) {
  if ( activities[i].attrib['android:name'] === 'com.whatever.app' ) {
    test.ok(true);
  }
}

The line if ( activities[i].attrib['android:name'] === 'com.whatever.app' ) { is largely a guess.

I don't know how the parser handles namespaced attributes. When in doubt, just dump the whole activities[i].attrib to the console and see what the parser did. Adapt the above code accordingly. I'm afraid that's as close as you will get with that kind of limited XPath support.

Post a Comment for "Searching For Xpath Expression With Colon In Attribute Name Throws Exception (node.js Elementtree Module)"