MSXML4 - Checking XML node for named attribute

I have encountered a problem when trying to read single node values from an xml document using MSXML4 and VB6.

(The xml data is retrieved from SQL Server 2000 using the SELECT FOR XML feature. The xml result of such a query does not include any tag or attribute for columns that has value NULL.)

When trying to read the value of an attribute that doesn’t exist, I get a run-time error (91): Object variable or with block not set.
So I have to check if a specific (named) attribute exists before I try to read it’s value.

Example:
XMLNode.Attributes.getNamedItem(“nameofAttribute”).Text
If the node doesn’t have an attribute named “nameofAttribute”, I get the run-time error.

I have looked for a way to check if a node has a named attribute, but not found anything. Can anyone help me?


Dim strText As String

'Check to see if attribute exists
If Not XMLNode.Attributes.getNamedItem("nameofAttribute") Is Nothing Then
	strText = XMLNode.Attributes.getNamedItem("nameofAttribute").Text
End If

It works… Simple as that. :blush:
My run-time error must have come from somewhere else…

Thanks!

Hi,

This is Suresh Vadivelu from Chennai.

You need to write a wrapper function, say GetAttributeByName
param p_strAttrName - the attribute whose value you want to retrieve
param p_objNode- the node containing the attribute

VBCode:
Public Function GetAttributeByName(ByVal p_strAttrName As String, ByVal p_objNode As IXMLDOMNode) As String

Dim objAttrlist As IXMLDOMNamedNodeMap
Dim objAttrNode As IXMLDOMAttribute
Dim strAttribute As String
Dim strErrMsg As String

On Error GoTo HandleError
'Extracts all the attributes from the node
If Not p_objNode Is Nothing Then
    Set objAttrlist = p_objNode.Attributes
    If Not objAttrlist Is Nothing Then
        'get the attribute node for the attribute name passed as parameter
        Set objAttrNode = objAttrlist.getNamedItem(p_strAttrName)
        If Not objAttrNode Is Nothing Then
            strAttribute = objAttrNode.Text
        End If
    End If
End If
GetAttributeByName = strAttribute
Exit Function

HandleError:
//write ur code

End Function

Hope this shud help u.
Will appreciate your feedback.

your code was useful as a beginner for me to get the attribute values.
Thanks
Jelf
Chennai

:cool: I have a problem in accessing a specific tag without considering the same tag inside child nodes.

The problem is:
<bib>
<au>
<fnm> Jelfy</fnm>
<snm>Mary</snm>
</au>
<au>
<fnm> Sumitha</fnm>
<snm>Susan</snm>
</au>
<eds>
<au>
<fnm> Joy</fnm>
<snm>Peter</snm>
</au>
<au>
<fnm> Flora</fnm>
<snm>Sania</snm>
</au>

&lt;/eds&gt;

</bib>
Here I want only Jelfy Mary and Sumitha Susan,the <au> inside <eds>
I dont want to extract.I used getelementbytagname,select singlenodes etc but it is fetching all the 4 au tags.
I want only the first 2.Can u help me? :party: