Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Visual Basic And XML

Posted on 2004-10-03
24
Medium Priority
?
364 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 11
  • 6
  • 4
  • +1
24 Comments
 
LVL 26

Expert Comment

by:Rejojohny
ID: 12211187
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
ID: 12211353
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
ID: 12215662
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 2

Author Comment

by:gerrymcd
ID: 12217398
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
ID: 12217437
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
ID: 12217543
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
ID: 12217599
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
ID: 12217757
>>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
ID: 12218738
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 105 total points
ID: 12223756
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
ID: 12223760
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
ID: 12228228
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
 
LVL 10

Expert Comment

by:anv
ID: 12234092
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 120 total points
ID: 12234672
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
ID: 12238351
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
ID: 12238629
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
ID: 12242918
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
ID: 12246223
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
ID: 12251474
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
ID: 12251523
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
ID: 12307150
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
ID: 12308224
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
ID: 12310612
No i just only give A if the solution works without me doing to much thinking. :)
0
 
LVL 2

Author Comment

by:gerrymcd
ID: 12310627
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
JavaScript has plenty of pieces of code people often just copy/paste from somewhere but never quite fully understand. Self-Executing functions are just one good example that I'll try to demystify here.
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

604 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