Tim:.. said:
Hi,
Possibly a very simple question but how do I get a value out of an
XML document so I can play with it in ASP.
E.G: <Name>Tom</Name>
How do I pull the work tom into asp.
Thanks
Let's make it a little more realistic. Start with this:
dim xmldoc, sName, sID
dim oNameNode
set xmldoc=createobject("msxml2.domdocument")
xmldoc.loadxml "<Names><Name id=""23"">Tom" & _
"</Name><Name id=""24"">Jack</Name></Names>"
This xml document has a root element (documentelement) called Names. This
root element has two child nodes. At this point you have several options:
If you know that the node whose text you wish to read has no child nodes:
1. If you know the location of the node containing the text you wish to
retrieve, then:
sName=xmldoc.documentelement.childnodes(0).text
'sName will contain "Tom"
sName=xmldoc.documentelement.childnodes(1).text
'sName will contain "Jack"
2. If you do not know which of the two nodes has the name "Tom", but you
know the id is 23, then you can use selectSingleNode:
dim oNameNode
'this should be a single line - your newsreader may break it:
set oNameNode = xmldoc.selectSingleNode("/Names/Name[@id='23']")
sName=oNameNode.text
Or, if you know the name "Tom", but wish to retrieve the id:
set oNameNode = xmldoc.selectSingleNode("/Names/Name[.='Tom']")
sID=oNameNode.getAttribute("id")
If there is a possibility that the node has child nodes, such as:
xmldoc.loadxml "<Names><Name id=""23"">Tom" & _
"<Address>13 Test Rd</Address></Name>" & _
"<Name id=""24"">Jack" & _
"<Address>14 Test Rd</Address></Name>" & _
"</Names>"
You can select the proper name node as above, but the text property will not
work well, because this:
sName=oNameNode.text
will contain this:
Tom13 Test Rd
In other words, the text property contains " ... the text content of the
node or the concatenated text representing the node and its descendants."
It is not intuitive, but with this xml: <Name>Tom</Name>, the Name node
actually has a child node whose node type is "text". The value of that node
(its nodeValue) is "Tom". It is as if the structure really was this:
<Name><text>Tom</text></Name>
If you know the structure, i.e., if you know the first child node of the
Name node will always contain the text you want, then you can do this:
sName=oNameNode.childnodes(0).nodevalue
However, if you are not sure of the structure, you will need to loop through
the childnodes until you get to the text node. For example:
xmldoc.loadxml "<Names><Name id=""23"">" & _
"<Address>13 Test Rd</Address>Tom</Name>" & _
"<Name id=""24"">Jack" & _
"<Address>14 Test Rd</Address></Name>" & _
"</Names>"
dim oNameNode,oNode, i
const NODE_TEXT=3
set oNameNode =xmldoc.documentelement.childnodes(0)
for i = 0 to oNameNode.childnodes.length - 1
set oNode=oNameNode.childnodes(i)
if oNode.nodeType= NODE_TEXT then
sName = oNode.nodevalue
exit for
end if
next
HTH,
Bob Barrows