Friday, February 5, 2010

XML DOM and Xpath Snippets

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

1 comment:

  1. Hi Asiq,

    I like your post and the way you have the XML DOM and Xpath Snippets for the testing community to understand and reuse.

    This surely makes it a candidate on my blog which has the best articles and posts across the web.

    Do mail me at aditya_kalra@ymail.com and let me know if it is fine i add this to my blog.

    My blog: http://go-gaga-over-testing.blogspot.com/

    Best Regards,
    Aditya Kalra

    ReplyDelete