all groups > dotnet xml > april 2005 >
You're in the

dotnet xml

group:

Syntax to get contents of a specific node


Syntax to get contents of a specific node JoBean
4/29/2005 7:04:02 PM
dotnet xml:
I think this is a simple Q but I cannot get the syntax right. I want to
specify the node name and get its contents. I do not want to loop through and
grab the contents of all child nodes - which the code below is doing fine. I
want to replace the inner loop by specifying the node name (name,
description) - Everything I try returns an obj ref error. Can someone please
point me in the right direction? Many thanks - JoBean

'CODE BEHIND MY ASPX PAGE============
Private m_doc As New XmlDocument
m_doc.Load("c:\myXMLDoc.xml")
Dim xmlNodes As XmlNodeList = m_doc.DocumentElement.ChildNodes
Dim siteNode As XmlNode

For Each siteNode In xmlNodes

Dim propNode As XmlNode

For Each propNode In siteNode

'returns all props for a site node
Response.Write(propNode.InnerText & "<br>")

Next propNode

Next siteNode

'XML FILE CONTENTS==============
<?xml version="1.0" encoding="utf-8" ?>
<MyList>
<Site>
<name>Name1</name>
<description>Desc1</description>
</Site>
<Site>
<name>Name1</name>
<description>Desc2</description>
</Site>
</MyList>

'RESULTS OF EXECUTING CODE SNIPPET==========
Returns:
Name1
Desc1
Name2
RE: Syntax to get contents of a specific node Ajit
4/30/2005 4:30:13 AM
If you need to access a specific node, then you should be using an XPath query.
You can reach to your specific node as follows:
m_doc.SelectSingleNode("Xpath query")

[quoted text, click to view]
RE: Syntax to get contents of a specific node JoBean
4/30/2005 3:58:02 PM
[quoted text, click to view]

Can you please help me with the syntax? I am continually coming up with a
Object Reference Not Set To An Instance Of An Object error, and I can't
figure out where I'm going wrong. Thank you so much for any help.

Dim x As String = m_doc.SelectSingleNode("/Sites/Site[1]/description").Value
Response.Write(x & "<br>")

The xml file is structured like so:
<Sites>
<Site>
<description>XYZ</description>
</Site>
<Site>
<description>ABC</description>
</Site>
</Sites>
Re: Syntax to get contents of a specific node JoBean
5/2/2005 6:16:12 AM
THANK YOU SO MUCH!!!

[quoted text, click to view]
Re: Syntax to get contents of a specific node Derek Harmon
5/2/2005 7:03:06 AM

[quoted text, click to view]

x is Nothing. Elements don't have values, they can only have child nodes.

Dim descriptionElem As XmlNode = m_doc.SelectSingleNode( "/Sites/Site[1]/description")
Dim x As String = descriptionElem.FirstChild.Value
If ( Not x Is Nothing )
Response.Write( x & "<br>" )

or alternately, use the XPath expression "/Sites/Site[1]/description/text()" with your
original code (although checking whether x is nothing is still a good idea).


Derek Harmon

AddThis Social Bookmark Button