MSXML: testing for getNamedItem before use

D

DrewM

I have an xml document fragment that I'm trying to process:

<field id="summary" type="textarea" label="Summary" />
<field id="content" type="wysiwyg" label="Content" />
<field id="status" type="hidden" />

(this is part of a bigger document loaded into XML DOM)

I'm looping through the <field> elements and extracting their attributes
into variables:

<%
for i = 0 to oFields.length-1
nId = oFields(i).attributes.getNamedItem("id").text
sType = oFields(i).attributes.getNamedItem("type").text
sLabel = oFields(i).attributes.getNamedItem("label").text

...
next
%>

The problem arises with the label attribute, because it is optional.
Trying to retrieve the text of a non-existent attribute throws an error
"Object required: 'oFields(...).attributes.getNamedItem(...)' ".

How can I test for this so as to gracefully avoid the error?

I've tried isNull() and isObject(), but these don't help. I'm beginning
to think that the only way to do it is to throw an error and trap it.
(Yuck).

Any ideas?

Thanks

Drew
 
R

Robert May

Try this (I'm assuming that this is VBScript):

for i = 0 to oFields.length-1
nId=GetAttributeValue(oFields(i),"id")
sType=GetAttributeValue(oFields(i), "type")
sLabel=GetAttributeValue(oFields(i), "label")

...
next

Function GetAttributeValue(byval p_sNode, byval p_sName)
dim oNode ' this will be an XmlNode object
dim sValue

sValue=""

set oNode=p_sNode.attributes.getNamedItem(p_sName)

if Not oNode is Nothing then
sValue=oNode.text
End If

GetAttributevalue=sValue

End Function
 
D

DrewM

Robert said:
Try this (I'm assuming that this is VBScript):

for i = 0 to oFields.length-1
nId=GetAttributeValue(oFields(i),"id")
sType=GetAttributeValue(oFields(i), "type")
sLabel=GetAttributeValue(oFields(i), "label")
...
next

Function GetAttributeValue(byval p_sNode, byval p_sName)
dim oNode ' this will be an XmlNode object
dim sValue
sValue=""
set oNode=p_sNode.attributes.getNamedItem(p_sName)
if Not oNode is Nothing then
sValue=oNode.text
End If
GetAttributevalue=sValue
End Function

Thanks, Robert. That was exactly what I needed.

+1 beer.


drew.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top