Vba xpath in vba in Excel
XPath is a syntax for defining parts of an XML document
XPath uses path expressions to select nodes or node-sets in an XML document
XPath expressions can be used in JavaScript, Java, XML Schema, PHP, Python, C and C++, and lots of other languages.
XPath contains a library of standard functions
XPath can be used to navigate through elements and attributes in an XML document.
With the help of various elements we saw in the previous chapter, let us see how to read a XML document.
Consider the following XML document as an Example.
- <?xml�version="1.0"�encoding="UTF-8"?>
- <Agencies>
- <Contractor>
- ����<name>Bhandhan Servicing</name>
- ����<service_type>Marriage arrangement</service_type>
- ����<description>
- All Services related to marriages
- ���</description>
- </Contractor>
- <Contractor>
- ����<name>VS functions</name>
- ����<service_type>Party arrangements</service_type>
- ����<description>
- Official get together, birthday party arrangements.
- ����</description>
- </Contractor>
- <Contractor>
- ����<name>Swami services</name>
- ����<service_type>Spiritual Services</service_type>
- ����<description>
- ��� Ganapathi homam, New home poojas performed.
- ����</description>
- </Contractor>
- <Contractor>
- ����<name>B Plus Services</name>
- ����<service_type>Blood Donation</service_type>
- ����<description>
- ��� Conducts Blood donation camps, organizing emergency blood donation
- ����</description>
- ����<calories>600</calories>
- </Contractor>
- </Agencies>
The following snippet shows how to traverse and read data from the above XML.
- Sub TestXML()
- ����Dim xml_doc As Object
- ����Set xml_doc = CreateObject("MSXML2.DOMDocument")
- ����xml_doc.async = False: xml_doc.validateOnParse = False
- ����xml_doc.Load (<xml_file_name>)
- ����'Get Document Elements
- ����Set lists = xml_doc.DocumentElement
- ����'Get first child ( same as ChildNodes(0) )
- ����Set getFirstChild = lists.FirstChild
- ����'Print first child XML
- ����Debug.Print getFirstChild.XML
- ����'Print first child Text
- ����Debug.Print getFirstChild.Text
- ����Set xml_doc = Nothing
- End Sub