Link to home
Start Free TrialLog in
Avatar of gerrymcd
gerrymcdFlag for Ireland

asked on

Visual Basic And XML

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>

Avatar of Rejojohny
Rejojohny
Flag of United States of America image

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 ...
Avatar of redzoneglobal
redzoneglobal

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?
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..
Avatar of gerrymcd

ASKER

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.
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.
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.
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.
>>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 ...


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>
-------------^"
ASKER CERTIFIED SOLUTION
Avatar of anv
anv

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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>
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?
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 ..
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
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 ..
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
try this and let me know what u get ....

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



if i take out the "<mytable> tags i get 1 if i leave them in i get 1.  im totaly lost here.
it appears the the line;
Set lobjNodesList = lobjNodesList.Item(0)

gives the error
"Object doest support this poperty or method"
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
ten probably my answer should have been accepted and "any"'s answer as "assisted"  .. any particular reason for a grade B?
No i just only give A if the solution works without me doing to much thinking. :)