XML DOM and Xpath Snippets - Asiq


In this article I am going to explain about the XML DOM methods and Xpath queries.

The Example XML Document Used For This Article



#1: Finding Elements by Attributes
If you want to access the name of the employee two, write attribute filter condition in your xpath query.
/Employees/Employee[@id='002']

Code:
gStrOrPath="C:\ Test.xml"'Path of your XML
Set gObjXmlOR = CreateObject( "Microsoft.XMLDOM")
gObjXmlOR.Async = "False"
gObjXmlOR.Load(gStrOrPath)
StrXQuery="/Employees/Employee[@id='002']" ' Attribute filter condition in your Xpath query
Msgbox gObjXmlOR.documentElement.selectSingleNode(StrXQuery).Text


The msgbox displays the child element’s text (I.e. Peter).

#2: Finding Elements with Text
Here I have written Xpath query to find the employee Peter’s gender using his name.
/Employees/Employee/name[.='Peter']

Code:
StrXQuery ="/Employees/Employee/name[.='Peter']" ' Text filter condition
Msgbox gObjXmlOR.documentElement.selectSingleNode(StrXQuery). Attributes.getNamedItem("gender").Text


The msgbox displays Sam’s gender as in the XML.

#3: Checking an Element has child or not
To find an element has child or not, then use XML Dom hasChildNodes method.
As per the example XML document, I am finding the employee node has child or not.

StrXQuery="/Employees/Employee[@id='002']
Msgbox gObjXmlOR.documentElement.selectSingleNode(StrXQuery).hasChildNodes


#4: Checking Errors in XML

Set gObjXmlOR = CreateObject("Microsoft.XMLDOM")
gObjXmlOR.async = False
gObjXmlOR.load("Test.xml")
If gObjXmlOR.parseError.errorCode <> 0 Then
  MsgBox("Parse Error line " & gObjXmlOR.parseError.line & ", character " & _
  gObjXmlOR.parseError.linePos & vbCrLf & gObjXmlOR.parseError.srcText)


End If

Source: XML DOM and Xpath Snippets - Asiq Ahamed

Comments

  1. Anonymous9/4/13

    Hi Aditya,

    Like XPath Checker / FireBug,if there any addons by which we check the CSS path.

    Thanks
    Satya

    ReplyDelete
  2. Here are more tools:
    http://go-gaga-over-testing.blogspot.in/2013/02/six-tools-for-selenium-object.html

    ReplyDelete
  3. Good Post. I like your blog. Thanks for Sharing
    Visit us: ui path online training
    Visit us: uipath training in hyderabad

    ReplyDelete

Post a Comment

Popular posts from this blog

Software Testing @ Microsoft

Trim / Remove spaces in Xpath?