Hi... I am working on a simple program (in VB.net) that will grab the
values of elements out of an XML file that are tagged as
"databasePath"... My program works, but I am getting too many
results. I need to limit the scope of the program to only include the
string value from the element that has a parent of "numberone", and
not both "numberone" and "numbertwo". I don't know if "numberone" is
a node, or what the correct term for it is - I am not too well-versed
in XML. :) I'm getting two lines of output in the console - both
databasePath strings from both the numberone section and the numbertwo
section. Is there any way I can limit the results to just the
numberone section, or numbertwo section by themselves?
My code is as follows, and the XML example is below that. Any help
would be greatly appreciated! Thanks!
VB Code:
Private Sub GetProgs()
Dim objReader As New XmlTextReader(strDASPath)
While objReader.Read()
If objReader.MoveToContent() = XmlNodeType.Element And
objReader.Name = "databasePath" Then
Console.WriteLine(objReader.ReadString())
End If
End While
End Sub
XML Example:
<?xml version="1.0"?>
<!DOCTYPE dasconfig SYSTEM "dasconfig.dtd" >
<dasconfig>
<global>
<annotation>
<advancedUser>true</advancedUser>
</annotation>
</global>
<dataset name="SampleData">
<numberone>
<database>
<Access>
<databasePath>C:\dvlp\test\numberone.mdb</
databasePath>
</Access>
</database>
</numberone>
<numbertwo>
<database>
<Access>
<databasePath>C:\dvlp\test\numbertwo.mdb</databasePath>
</Access>
</database>
</numbertwo>
</dataset>
</dasconfig>
syvman@gmail.com - 28 Sep 2007 23:22 GMT
I have figured out a way to make it skip the "numbertwo" items, by
placing the following if then statement BEHIND my original if then
statement:
If objReader.Name = "numbertwo" Then
objReader.Skip()
End If
However, I'm still a little confused. Why does this not work when I
place the same statement ABOVE the original if then statement?
Shouldn't it skip the children of numbertwo regardless of where it
encounters them in the loop?
syvman@gmail.com - 29 Sep 2007 00:18 GMT
Ok - I figured that out, too... Looks like the MoveToContent() method
is the key here - without it, the reader won't move to different lines
in the xml file. My new code is posted below, and works flawlessly:
While objReader.Read()
objReader.MoveToContent()
If objReader.Name = "numbertwo" Then
objReader.Skip() 'Skip all children
End If
If objReader.Name = "databasePath" Then
Console.WriteLine(objReader.ReadString())
End If
End While
Any insight from a more knowledgable person would be appreciated...
Just in case my understanding is flawed. Thanks!!!