Solved

Visual Basic And XML

Posted on 2004-10-03
24
349 Views
Last Modified: 2013-11-25
im trying to learn some XML and i reckon i have the basics.
I have a xml document that i created from my database (hard coded) and i want to be able to read it.  As i want to use it for a quick import and export of my database.  I dont know how you read XML in VB6 can some help?

<?xml version="1.0" encoding="UTF-8" ?>
<mytable>


<record>
<Filename>D:\songs\themes\2001 Space Oddessy - Theme.mp3</Filename>
<crc>1808384</crc>
<artist>200 Space Oddessy</artist>
<track>200 Space Oddessy - Theme</track>
<album>Unknown</album>
<year>1964</year>
<genre>Soundtrack</genre>
<playcount>2</playcount>
<rating>0</rating>
</record>

<record>
<Filename>D:\songs\themes\Alabama 3 - Woke Up This Morning - Sopranos Soundtrack.mp3</Filename>
<crc>D60080AE</crc>
<artist>Alabama 3</artist>
<track>Woke Up This Morning</track>
<album>Sopranos Soundtrack</album>
<year>1999</year>
<genre>Soundtrack</genre>
<playcount>10</playcount>
<rating>5</rating>
</record>

</mytable>

0
Comment
Question by:gerrymcd
  • 11
  • 6
  • 4
  • +1
24 Comments
 
LVL 26

Expert Comment

by:Rejojohny
Comment Utility
u could use Microsoft XML (MSXML) .. add a reference to Microsoft XML in ur project .. look in MSDN for "XMLDOM" and "XPATH" ... u will find lots of examples on loading xmlstring into XMLDOM and parsing it ...
0
 
LVL 1

Expert Comment

by:redzoneglobal
Comment Utility
http://www.chilkatsoft.com/
Has a great VB ActiveX control for parsing XML files, and it's FREE! :)

We have used this control in many applications, and it "screams" through
huge XML files (50MB+), works well with online CGI apps also.
It also will validate XML files, that MSXML will freeze up on.

Why re-invent the wheel?
0
 
LVL 10

Expert Comment

by:anv
Comment Utility
chek this

    Dim strXMLFilePath As String
    Dim objXMLDOM As New MSXML2.DOMDocument26
    Dim objNodes As IXMLDOMNodeList
    Dim objBookNode As IXMLDOMNode
    Dim objFSO As Object
    Dim ObjFile As Variant
    Dim ObjFolder As Variant
Private Sub Form_Load()
        Call ReadXMLFiles
End Sub
Sub ReadXMLFiles()
On Error GoTo ErrorHandler   ' Enable error-handling routine.
    Set objFSO = CreateObject("Scripting.FileSystemObject")
     strXMLFilePath = App.Path
     If objFSO.FolderExists(strXMLFilePath) Then
       Set ObjFolder = objFSO.GetFolder(strXMLFilePath)
       For Each ObjFile In ObjFolder.Files
         If InStr(ObjFile.Type, "XML") > 0 Then
            Call LoadXMLFiles(strXMLFilePath, ObjFile.Name)
            Call ReadFile
            'FileCopy SourceFile, TargetFile '// If you want to copy from some Different location
            'Kill (strXMLFilePath & ObjFile.Name)'// You Can Kill the File if you want after reading
         End If
       Next
     End If
     
     Set ObjFolder = Nothing
     Set ObjFile = Nothing
     Set objFSO = Nothing
     Exit Sub           ' Exit to avoid handler.
ErrorHandler:          ' Error-handling routine.
    Set ObjFolder = Nothing
    Set ObjFile = Nothing
    Set objFSO = Nothing
    End
End Sub

Sub LoadXMLFiles(strXMLFilePath As String, strXMLFileName As String)
On Error GoTo ErrorHandler   ' Enable error-handling routine.
    objXMLDOM.async = False
    objXMLDOM.Load (strXMLFilePath & "\" & strXMLFileName)
    Exit Sub           ' Exit to avoid handler.
ErrorHandler:            ' Error-handling routine.
    Set objXMLDOM = Nothing
    End
End Sub
Sub ReadFile()
On Error GoTo ErrorHandler   ' Enable error-handling routine.
Dim NodeValue
    Set objNodes = objXMLDOM.selectNodes("MainNode")
   For Each objBookNode In objNodes
    If objBookNode.selectNodes("Node1").length <> 0 Then
         NodeValue = objBookNode.selectSingleNode("Node1").nodeTypedValue
         Debug.Print NodeValue
    End If
    If objBookNode.selectNodes("Node2").length <> 0 Then
         NodeValue = objBookNode.selectSingleNode("Node2").nodeTypedValue
         Debug.Print NodeValue
    End If
    Next objBookNode
    Set objNodes = objXMLDOM.selectNodes("MainNode/Node3/SubNode31")
    For Each objBookNode In objNodes
      If objBookNode.selectNodes("SubNode311").length <> 0 Then
         NodeValue = objBookNode.selectSingleNode("SubNode311").nodeTypedValue
         Debug.Print NodeValue
      End If
      If objBookNode.selectNodes("SubNode312").length <> 0 Then
         NodeValue = objBookNode.selectSingleNode("SubNode312").nodeTypedValue
         Debug.Print NodeValue
      End If
    Next objBookNode
    Set objNodes = objXMLDOM.selectNodes("MainNode/Node4/Node41")
    For Each objBookNode In objNodes
      If objBookNode.selectNodes("Node411").length <> 0 Then
         NodeValue = objBookNode.selectSingleNode("Node411").nodeTypedValue
         Debug.Print NodeValue
      End If
      If objBookNode.selectNodes("Node412").length <> 0 Then
         NodeValue = objBookNode.selectSingleNode("Node412").nodeTypedValue
         Debug.Print NodeValue
      End If
    Next objBookNode
    Exit Sub      ' Exit to avoid handler.
ErrorHandler:       ' Error-handling routine.
   End
End Sub

u need to have the xml engine installed on ur PC...

add reference to Microsoft XML v2.6 or whichever version of XML engine u have..
0
 
LVL 2

Author Comment

by:gerrymcd
Comment Utility
Those examples are quite difficult for a newbie to understand in XML.  Can you please reference my xml above.  As i cant get it to work with any of the examples posted.  thanks.
0
 
LVL 1

Expert Comment

by:redzoneglobal
Comment Utility
gerry,

Did you bother to go to Chilkat's site?
They have a nice tutorial for newbies, and several example programs with "real world" examples.
Coding for XML parsing is inherently cryptic "looking" as the control is doing most of the work.
0
 
LVL 2

Author Comment

by:gerrymcd
Comment Utility
re; redzoneglobal

i did while it looks good & looks easy i cant get it to work work with my xml file, im still testing it.
0
 
LVL 1

Expert Comment

by:redzoneglobal
Comment Utility
Your XML file is easy to parse using ChilKat's control.
I'd be happy to write out the code for you, to
get you started.

Once you see a sample app. using your data, further
use of the control is usually pretty simple...

Just let me know... and we can make arrangements
to get me your file that you want to parse.

K.
0
 
LVL 26

Expert Comment

by:Rejojohny
Comment Utility
>>im trying to learn some XML and i reckon i have the basics.
what do u mean by this??

>> dont know how you read XML in VB6 ..
do u mean u do not know to load an xml file using XMLDOM .. then here is the code for u ..

add refrence to Microsoft XML,v2.x  or v3.0 or v4.0 whichever u have ..

write this code in some button click event

        Dim lobjXMLDoc as New DOMDocument30
Dim strXML as string

strXML = "<?xml version="1.0" encoding="UTF-8" ?>" & _
"<mytable>"  & _
"<record>" & _
"<Filename>D:\songs\themes\2001 Space Oddessy - Theme.mp3</Filename>" & _
"<crc>1808384</crc>" & _
"<artist>200 Space Oddessy</artist>" & _
"<track>200 Space Oddessy - Theme</track>" & _
"<album>Unknown</album>" & _
"<year>1964</year>" & _
"<genre>Soundtrack</genre>" & _
"<playcount>2</playcount>" & _
"<rating>0</rating>" & _
"</record>" & _
"</mytable>"

    lobjXMLDoc.async = False
    lobjXMLDoc.loadXML(strXML)
        If lobjXMLDoc.parseError <> 0 Then
            MsgBox lobjXMLDoc.parseError.reason, vbInformation, mstrApplicationTitle
        End If
     msgbox lobjXMLDoc.xml

I hope now u get the basics .. pls read MSDN ... it will help u to try things out urself and come with specific questions ...


0
 
LVL 2

Author Comment

by:gerrymcd
Comment Utility
thnaks im just running through that code;

My xml in full is at;
http://homepage.eircom.net/~mrdj/test.xml

View it in IE

when i view it in Firefox it says;

"XML Parsing Error: not well-formed
Location: http://bratch.no-ip.com/irishbloke/test.xml
Line Number 1168, Column 14:<genre>Rock & Roll</genre>
-------------^"
0
 
LVL 10

Accepted Solution

by:
anv earned 35 total points
Comment Utility
hi gerrymcd

U need to check the following procedure which reads or parses an XML file..

Sub ReadFile()
On Error GoTo ErrorHandler   ' Enable error-handling routine.
Dim NodeValue

     ' objXMLDOM is DOM or Document Object Model object..refer above code for declaration..
    Set objNodes = objXMLDOM.selectNodes("MainNode")

     'Main Node is name of the top most node in the xml file..
'Replace it with the name of the topmost node in ur file..



'Check for each sub nodes under the main node...
'and get their attribute values..

For Each objBookNode In objNodes
  If objBookNode.selectNodes("Node1").length <> 0 Then 'If length is not 0 then continue

         NodeValue = objBookNode.selectSingleNode("Node1").nodeTypedValue
         Debug.Print NodeValue
    End If
 
  If objBookNode.selectNodes("Node2").length <> 0 Then
         NodeValue = objBookNode.selectSingleNode("Node2").nodeTypedValue
         Debug.Print NodeValue
    End If

Next objBookNode

    Set objNodes = objXMLDOM.selectNodes("MainNode/Node3/SubNode31")
'Select Sub node of main node/node3
'Get all subnodes of nodes3 and store their values

For Each objBookNode In objNodes
  If objBookNode.selectNodes("SubNode311").length <> 0 Then
         NodeValue = objBookNode.selectSingleNode("SubNode311").nodeTypedValue
         Debug.Print NodeValue
      End If
      If objBookNode.selectNodes("SubNode312").length <> 0 Then
         NodeValue = objBookNode.selectSingleNode("SubNode312").nodeTypedValue
         Debug.Print NodeValue
      End If
Next objBookNode

'Same as for node3...

    Set objNodes = objXMLDOM.selectNodes("MainNode/Node4/Node41")
    For Each objBookNode In objNodes
      If objBookNode.selectNodes("Node411").length <> 0 Then
         NodeValue = objBookNode.selectSingleNode("Node411").nodeTypedValue
         Debug.Print NodeValue
      End If
      If objBookNode.selectNodes("Node412").length <> 0 Then
         NodeValue = objBookNode.selectSingleNode("Node412").nodeTypedValue
         Debug.Print NodeValue
      End If
    Next objBookNode
    Exit Sub      ' Exit to avoid handler.

ErrorHandler:       ' Error-handling routine.
   End
End Sub


'In above code the values of the nodes are bein printed into the immediate window..

if u want u can store into database or text file or into an array...etc..

0
 
LVL 10

Expert Comment

by:anv
Comment Utility
the format for the file used in above code is like..
<MainNode>
  <Node1>Node1</Node1>
  <Node2>Node2</Node2>
- <Node3>
- <SubNode31>
  <SubNode311>SubNode311</SubNode311>
  <SubNode312>SubNode312</SubNode312>
  </SubNode31>
  </Node3>
- <Node4>
- <Node41>
  <Node411>Loop1</Node411>
  <Node412>Loop1</Node412>
  </Node41>
- <Node41>
  <Node411>Loop2</Node411>
  <Node412>Loop2</Node412>
  </Node41>
- <Node41>
  <Node411>Loop3</Node411>
  <Node412>Loop3</Node412>
  </Node41>
  </Node4>
  </MainNode>
0
 
LVL 2

Author Comment

by:gerrymcd
Comment Utility
the main problem i have with the xml file is i dont kno how to enumerate through the file.  I have a lot of <record> tags.  in each is data.  when i read one of these records how do i move on to the next one?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 10

Expert Comment

by:anv
Comment Utility
add above code into a loop like this

 While Not (objnode Is Nothing)

Select Case objnode.NodeName
            Case "RequestData"
                'text1 = text1 + "NODE:" & objnode.NodeName & objnode.nodeValue & vbNewLine
                For Each objAttr In objnode.Attributes
                    Select Case objAttr.NodeName
                        Case "PolicyNumber": 'Do something
                    End Select
                Next
           
            Case "CalculationResults"
                For Each objAttr In objnode.Attributes
                    Select Case objAttr.NodeName
                        Case "CostDataAsOfDate": 'do something
                    End Select
                Next
            Case "CoverageASummary":
                Dim objTempNode As IXMLDOMNode
                Set objTempNode = objnode.firstChild
                ' check this section iteratively
                While Not (objTempNode Is Nothing)
                    If objTempNode.NodeName = "Item" Then
                        Set objAttr = objTempNode.Attributes(0)
                        Dim objTempAttr As IXMLDOMAttribute
                        Set objTempAttr = objTempNode.Attributes(1)
                            Select Case objAttr.nodeValue
                                Case "ArchitectsFees": 'do something
                    End If
                    Set objTempNode = objTempNode.nextSibling
                Wend
                    Set objTempNode = objTempNode.nextSibling
Wend

hope this will help u ..
0
 
LVL 26

Assisted Solution

by:Rejojohny
Rejojohny earned 40 total points
Comment Utility
as i mentioned before .. use XPATH to do that .. i hope u had look into the code i have given above to load the xmlstring .. now add the following line

lstrSelect = "record"             'this is case-sensitive
Set lobjNodesList = mobjInvestmentTypeXMLDoc.selectNodes(lstrSelect)
if lobjNodesList.length > 0 then
  Set lobjNodesList = lobjNodesList.item(0)
  for lintCtr = 0 to lobjNodesList.length - 1
      msgbox lobjNodesList.item(lintCtr).childnodes(1).text 'this will give u the text of the tag "Filename"
  next
end if
0
 
LVL 2

Author Comment

by:gerrymcd
Comment Utility
re;Rejojohny
Yes i have looked at your code.  and it didnt work theres something not right.  i dont think one of the variables (the nodelist one is dimmed)

see here;
Dim lobjXMLDoc As New DOMDocument30
Dim strXML As String


strXML = "<?xml version=" & Chr(34) & "1.0" & Chr(34) & " encoding=" & Chr(34) & "UTF-8" & Chr(34) & "?>" & _
"<mytable>" & _
"<record>" & _
"<Filename>D:\songs\themes\2001 Space Oddessy - Theme.mp3</Filename>" & _
"<crc>1808384</crc>" & _
"<artist>200 Space Oddessy</artist>" & _
"<track>200 Space Oddessy - Theme</track>" & _
"<album>Unknown</album>" & _
"<year>1964</year>" & _
"<genre>Soundtrack</genre>" & _
"<playcount>2</playcount>" & _
"<rating>0</rating>" & _
"</record>" & _
"</mytable>"

Debug.Print strXML

    lobjXMLDoc.async = False
    lobjXMLDoc.loadXML (strXML)
    'lobjXMLDoc.Load "c:\test.xml"
        If lobjXMLDoc.parseError <> 0 Then
            MsgBox lobjXMLDoc.parseError.reason, vbInformation, mstrApplicationTitle
        End If
     MsgBox lobjXMLDoc.xml
     
     
    lstrSelect = "record"             'this is case-sensitive
    Set lobjNodesList = lobjXMLDoc.selectNodes(lstrSelect)
    If lobjNodesList.length > 0 Then
    Set lobjNodesList = lobjNodesList.Item(0)
    For lintCtr = 0 To lobjNodesList.length - 1
      MsgBox lobjNodesList.Item(lintCtr).childNodes(1).Text 'this will give u the text of the tag "Filename"
    Next
    End If
0
 
LVL 26

Expert Comment

by:Rejojohny
Comment Utility
ya, it is so .. i assumed that u would do the rest .. u will have to tweek it a little .. basically i have given u the code on how it will work .. u make changes wherever necessary ...
is option explicit on .. and what is the error that u get ..
0
 
LVL 2

Author Comment

by:gerrymcd
Comment Utility
re;Rejojohny  

no it just doesnt work the new part you added; no msgbox appears

lstrSelect = "record"             'this is case-sensitive
    Set lobjNodesList = lobjXMLDoc.selectNodes(lstrSelect)
    If lobjNodesList.length > 0 Then
    Set lobjNodesList = lobjNodesList.Item(0)
    For lintCtr = 0 To lobjNodesList.length - 1
      MsgBox lobjNodesList.Item(lintCtr).childNodes(1).Text 'this will give u the text of the tag "Filename"
    Next
    End If
0
 
LVL 26

Expert Comment

by:Rejojohny
Comment Utility
try this and let me know what u get ....

.....
Set lobjNodesList = lobjXMLDoc.selectNodes(lstrSelect)
msgbox lobjNodesList.length ...
  If lobjNodesList.length > 0 Then
.......



0
 
LVL 2

Author Comment

by:gerrymcd
Comment Utility
if i take out the "<mytable> tags i get 1 if i leave them in i get 1.  im totaly lost here.
0
 
LVL 2

Author Comment

by:gerrymcd
Comment Utility
it appears the the line;
Set lobjNodesList = lobjNodesList.Item(0)

gives the error
"Object doest support this poperty or method"
0
 
LVL 2

Author Comment

by:gerrymcd
Comment Utility
in the end Rejojohny 's code was what i needed and worked.  Thanks to all.

For future reference the answer;



Dim lobjXMLDoc As New DOMDocument30
Dim strXML As String, i As Integer


strXML = "<?xml version=" & Chr(34) & "1.0" & Chr(34) & " encoding=" & Chr(34) & "UTF-8" & Chr(34) & "?>" & _
"<mytable>" & _
"<record>" & _
"<filename>D:\songs\themes\2001 Space Oddessy - Theme.mp3</filename>" & _
"<crc>1808384</crc>" & _
"<artist>200 Space Oddessy</artist>" & _
"<track>200 Space Oddessy - Theme</track>" & _
"<album>Unknown</album>" & _
"<year>1964</year>" & _
"<genre>Soundtrack</genre>" & _
"<playcount>2</playcount>" & _
"<rating>0</rating>" & _
"</record>" & _
"<record>" & _
"<Filename>D:\songs\themes\Alabama 3 - Woke Up This Morning - Sopranos Soundtrack.mp3</Filename>" & _
"<crc>D60080AE</crc>" & _
"<artist>Alabama 3</artist>" & _
"<track>Woke Up This Morning</track>" & _
"<album>Sopranos Soundtrack</album>" & _
"<year>1999</year>" & _
"<genre>Soundtrack</genre>" & _
"<playcount>10</playcount>" & _
"<rating>5</rating>" & _
"</record>" & _
"</mytable>"


Debug.Print strXML

    lobjXMLDoc.async = False
    lobjXMLDoc.loadXML (strXML)
    'lobjXMLDoc.Load "c:\test.xml"
        If lobjXMLDoc.parseError <> 0 Then
            MsgBox lobjXMLDoc.parseError.reason, vbInformation, mstrApplicationTitle
        End If
     MsgBox lobjXMLDoc.xml
     
    lintCtr = 0
    lstrSelect = "mytable/record"             'this is case-sensitive
    Set lobjNodesList = lobjXMLDoc.selectNodes(lstrSelect)
    MsgBox lobjNodesList.length
   
    If lobjNodesList.length > 0 Then
    'Set lobjNodesList = lobjNodesList.Item(0)
    'MsgBox lobjNodesList.length
    For i = 0 To lobjNodesList.length - 1
      MsgBox lobjNodesList.Item(i).childNodes(0).Text 'this will give u the text of the tag "Filename"

    Next
    End If
0
 
LVL 26

Expert Comment

by:Rejojohny
Comment Utility
ten probably my answer should have been accepted and "any"'s answer as "assisted"  .. any particular reason for a grade B?
0
 
LVL 2

Author Comment

by:gerrymcd
Comment Utility
No i just only give A if the solution works without me doing to much thinking. :)
0
 
LVL 2

Author Comment

by:gerrymcd
Comment Utility
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Preface This is the third article about the EE Collaborative Login Project. A Better Website Login System (http://www.experts-exchange.com/A_2902.html) introduces the Login System and shows how to implement a login page. The EE Collaborative Logiā€¦
This article describes some techniques which will make your VBA or Visual Basic Classic code easier to understand and maintain, whether by you, your replacement, or another Experts-Exchange expert.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now