all groups > dotnet xml > september 2004 >
You're in the

dotnet xml

group:

How to get XML data out of an XML file



How to get XML data out of an XML file flycast
9/28/2004 11:11:02 AM
dotnet xml: I am trying to retrieve the Parameters first or second (0, 1 ,2) node from
the following XML file:

<?xml version="1.0" encoding="utf-8" ?>
<Robot xmlns="http://tempuri.org/RobotDefaults.xsd">
<Parameters>
<Name>Decker</Name>
</Parameters>
<Parameters>
<Name>A</Name>
</Parameters>
<Parameters>
<Name>B</Name>
</Parameters>
</Robot>

There will be more data than just a name for each Parameters node. Here is
my code:

Dim node As XmlNode = xmlDocument.SelectSingleNode("/Parameters")
RobotName.Text = node.SelectSingleNode("Name").InnerText

I get the dreaded "Object reference not set to an instance of an object."
The SelectSingleNode is not working because I am too dense to figure out how
to write the syntax for the XPAth. I have read the documentation all morning
and am still having trouble.

I have downloaded really nice software called VisualXPath and tried this
query string from it:
/def:Robot/def:Parameters[1]
This gets me a "System Error"

Can anybody show me how to retrieve the "x" number Parameter node from this
document?

Thanks,
Re: How to get XML data out of an XML file Derek Harmon
9/28/2004 8:38:12 PM
[quoted text, click to view]

Check whether node is Nothing, flycast, and you're less likely to feel dreadful.

If ( node Is Nothing ) Then
' Do Something Else.
Else
RobotName.Text = node.SelectSingleNode( "Name").InnerText
End If

I'll point out that the Else block can still produce a NullReferenceException,
if the Name node is not found (see next point).

: :
[quoted text, click to view]

Also try using the XmlNamespaceManager, adding the default namespace URI
of "http://tempuri.org/RobotDefaults.xsd" to it, and passing that along to Select-
SingleNode( ), like this,

Dim nsMan As XmlNamespaceManager = New XmlNamespaceManager( xmlDocument.NameTable)
nsMan.AddNamespace( "def", "http://tempuri.org/RobotDefaults.xsd")
Dim node As XmlNode = xmlDocument.SelectSingleNode( "/def:Robot/def:Parameters", nsMan)

[quoted text, click to view]

XPath lets you use position( ) = x in a predicate (which can be abbreviated to [x] almost like
a C/C++/C# array index). However in XPath, positions start numbering at 1 (so you can
retrieve the 1st Parameter, the 2nd Parameter, etc.). Ammend the previous code snippet
as follows to fetch the second parameter node,

' Code as before, now retrieving the second Parameter node of Robot.
Dim paramNumber As Integer = 2
Dim node As XmlNode = xmlDocument.SelectNodes( "/def:Robot/def:Parameters[" + CStr( paramNumber) + "]", nsMan)


Derek Harmon

Re: How to get XML data out of an XML file Victor Hadianto
9/29/2004 9:57:25 AM
[quoted text, click to view]

Try //Robot/Parameters

--
Victor Hadianto
http://www.synop.com/Products/SauceReader/




[quoted text, click to view]

AddThis Social Bookmark Button