dcsimg
Results 1 to 29 of 29
  1. #1

    Thread Starter
    Frenzied Member jdc20181's Avatar
    Join Date
    Oct 2015
    Location
    Indiana
    Posts
    1,049

    In all Honesty I don't know how to read/write XML files

    I know its crazy to be coding now for uh 3 years, and still not know databases, and xml files. As of right now, I am saving data into plain text, which is probably not the most ideal. I have worked on my web-browser project just for fun the last 5 years, publicly released in 2015, at first it didn't even have a way to save your history and for my newbie self I only used the internet control provided in VS. I later outgrew that and began learning in more depth. And switched to an open-source engine which it is built around. blah blah blah - onto the question/discussion:

    Currently I save, and write all the webbrowsing history manually (sort of speak) in plain text.

    I have come here before, and had help even improving WHERE the files are stored, however its HOW they are stored that is now come to pass that needs improved.

    How would you do this in xml? - Keeping everything pretty straight forward would be appreciated, I am starting to introduce myself with storing data more, as that is important to where I am in terms of learning/polishing my knowledge.



    Code:
        Public Sub Save_History()
            Dim HistoryPath As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) &
                             "\.\LightBrowseData" &
                             My.Settings.History
            Dim file As System.IO.StreamWriter
            file = My.Computer.FileSystem.OpenTextFileWriter(HistoryPath, True)
    
            file.WriteLine(CType(TabControl1.SelectedTab.Controls.Item(0), GeckoWebBrowser).Url.ToString())
    
            file.Close()
        End Sub
    Disclaimer: When code is given for example - it is merely a example. See my First CodeBank Submission Upgrading to the newest IE when using the Webbrowser control See my Second CodeBank SubmissionVB.NET - Recording History or changes using WebbrowserControl RichTextBox Textbox
    See my Third codebank submission VB.NET - Detecting Secure/Insecure Websites (ssl) w/ Webbrowser control See CodeBank Submission 4 A Simple Large View Calendar Control See my browser project BeffsBrowser Try my SpeedTest Project

    Unless said otherwise (e.g. From one of my projects thus, those are mostly licensed under MIT) - All Code snippets advice or otherwise that I post on this site, are expressly licensed under Creative Commons Attribution 4.0 International Please respect my copyrights.

  2. #2
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    3,619

    Re: In all Honesty I don't know how to read/write XML files


  3. #3
    Addicted Member
    Join Date
    Nov 2011
    Posts
    161

    Re: In all Honesty I don't know how to read/write XML files

    A Google search for "simple xml database" should pull up some info if it is a small database app your looking for, I found some interesting tutorials on Youtube.

    Once you get past the point of creating a datatable with a few data columns I'm pretty sure you will get further help on this forum with writing the code to add, delete and modify the data in your new database.

  4. #4
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    98,682

    Re: In all Honesty I don't know how to read/write XML files

    Quote Originally Posted by jdc20181 View Post
    I know its crazy to be coding now for uh 3 years, and still not know databases, and xml files.
    Databases? I'm a little surprised. XML files? I've been at VB.NET for 15 years and barely know anything beyond the most common types used. What I think is crazy is that you thought that posting here was your best first option rather than searching the web for yourself. I've been known to chastise beginners for not searching first on occasion. Someone with your level of experience really ought to know better. No one has to know everything but how to at least find the basic information on a subject is something that anyone with reasonable levels of computer experience should know these days.

    I know that there are those - perhaps even yourself - who will say that this post was unnecessary and unhelpful. I say that if it causes you to think to search first in future, whether by encouragement or guilt, then it has been helpful.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Frenzied Member jdc20181's Avatar
    Join Date
    Oct 2015
    Location
    Indiana
    Posts
    1,049

    Re: In all Honesty I don't know how to read/write XML files

    Quote Originally Posted by jmcilhinney View Post
    What I think is crazy is that you thought that posting here was your best first option rather than searching the web for yourself.
    I already spent much of the afternoon searching, reading, searching, reading repeat. Everything was either irrelevant to the task at hand, was for asp.net, or just was plainly awful in terms of amount of code it took to do something I already do with maybe 5 or 6 lines. I shouldn't need 50 lines to do one thing. I think one codeproject article I was reading had like 100-150 lines of code just to create a xml file. didn't even include reading.

    Code:
        Dim doc As XDocument = XDocument.Load("HistoryStorage.xml")
            For Each historyitem As XElement In doc.<history>.<entry>
                Dim url As String = historyitem.<url>.Value
                Dim title As String = historyitem.<site>.Value
                ListBox1.Items.Add(url & " - " & title)
            Next
        End Sub
    (Currently the path to the file is local, when its released its in the app data file)

    ______________________

    Looked over other's comments - pretty much the same thing, not detailed enough, isn't what I am looking for, or just plainly is more effort than its worth to do a simple task.

    I should be able to do something similar writing as the same as I did with plain text. All I need to do differently is create the element, and nest the data into it.

    I am sure I will figure it out before I go into work tomorrow.
    Disclaimer: When code is given for example - it is merely a example. See my First CodeBank Submission Upgrading to the newest IE when using the Webbrowser control See my Second CodeBank SubmissionVB.NET - Recording History or changes using WebbrowserControl RichTextBox Textbox
    See my Third codebank submission VB.NET - Detecting Secure/Insecure Websites (ssl) w/ Webbrowser control See CodeBank Submission 4 A Simple Large View Calendar Control See my browser project BeffsBrowser Try my SpeedTest Project

    Unless said otherwise (e.g. From one of my projects thus, those are mostly licensed under MIT) - All Code snippets advice or otherwise that I post on this site, are expressly licensed under Creative Commons Attribution 4.0 International Please respect my copyrights.

  6. #6
    Frenzied Member
    Join Date
    May 2014
    Location
    Central Europe
    Posts
    1,254

    Re: In all Honesty I don't know how to read/write XML files

    I do not think that it is anything crazy that you have never used XML or a database yet. You just did not have any Need to use these.
    What would be crazy is if you say that you never gonna need it and therefore have no interest in learning it.
    As a developer you are constantly challenged to learn new stuff and i think you are on the right way if you question if you maybe could do something better by learning new techniques.

    First Thing to note on XML files is that they are designed to store hierarchical data. For the way you plan to use it to store browser history this means that it does not give you any benefit as your data is flat and not hierarchical. but if you gonna store all your config to an XML as well, that could benefit from the hierarchical nature of XML. you could for example have a "Favorites" node with Folders and links underneath.

    here is a super simple example on how to create an XML file:
    Code:
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim xml As New Xml.XmlDocument
            Dim NewMainNode As Xml.XmlNode = xml.CreateElement("MainNode")
            xml.AppendChild(NewMainNode)
    
            For i As Int32 = 0 To 10
                Dim ChildNode As Xml.XmlNode = xml.CreateElement("ChildNode" & i)
                ChildNode.InnerText = "This is child #" & i
                NewMainNode.AppendChild(ChildNode)
            Next
    
            xml.Save("c:\kill\test.xml")
        End Sub
    there are multiple ways on how to read/write XML. The one i prefer is shown above and uses the Xml.XmlDocument class. be prepared that you will find other examples using different classes, so be careful not to mix them up.

  7. #7
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    31,608

    Re: In all Honesty I don't know how to read/write XML files

    Google "vb.net xml serialization"
    That's going to be the simplest way. Takes like 5 lines of code to serialize/deserialize something. So if you have your history in something like a List(Of) (which I hope you do) ... then it's a simple, easy peasy thing to do.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  8. #8
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,008

    Re: In all Honesty I don't know how to read/write XML files

    If using a file I prefer to use XElement. Here is some code with several sample sites. The last three sites are worth reading.

    Code:
            Dim smplSites As New List(Of String)
            smplSites.Add("http://www.vbforums.com/forumdisplay.php?25-Visual-Basic-NET")
            smplSites.Add("https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=vbgeneral")
            smplSites.Add("")
            smplSites.Add("")
            smplSites.Add("https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement?view=netframework-4.7.2")
            smplSites.Add("https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/xml/embedded-expressions-in-xml")
            smplSites.Add("https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/xml/xml-literals-overview")
    
            Dim histPath As String = "put path to xml file here, i.e. c:\foo.xml"
            Dim hist As XElement
    
            'to load from file
            ' hist = XElement.Load(histPath)
    
            'for testing use literals
            hist = <histories>
                   </histories>
    
            'save the sample sites
            For Each Site As String In smplSites
                ' XML literals and embedded expressions are the last two sites
                If Site <> "" Then
                    Dim aHist As XElement = <hist lastvisit=""><%= Site %></hist>
                    aHist.@lastvisit = DateTime.Now.ToString
                    hist.Add(aHist)
                End If
            Next
    
            'a simple query
            Dim qry As IEnumerable(Of XElement)
            qry = From s In hist.Elements
                    Where s.Value.Contains("docs.microsoft")
                    Select s
    
            'look at results
            For Each qr As XElement In qry
                Stop
            Next
    
            'to save
            ' hist.Save(histPath)
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  9. #9
    Fanatic Member
    Join Date
    Dec 2014
    Location
    VB6 dinosaur land
    Posts
    815

    Re: In all Honesty I don't know how to read/write XML files

    Many major browsers (i.e., Firefox and Chrome) use SQLite for history so it's time to learn databases.

  10. #10

    Thread Starter
    Frenzied Member jdc20181's Avatar
    Join Date
    Oct 2015
    Location
    Indiana
    Posts
    1,049

    Re: In all Honesty I don't know how to read/write XML files

    Quote Originally Posted by dbasnett View Post
    If using a file I prefer to use XElement. Here is some code with several sample sites.
    That actually worked better than expected. Thanks. I think what happened was everything was confusing there was a dozen different ways to do the same thing, but all with variants of the expected results.

    I ended up writing out, myself - the loading part of the task at hand - This works pretty good too, was surprised at the speed, as I have had issues with loading text files into listboxes before:

    Code:
          Dim doc As XDocument = XDocument.Load("HistoryStorage.xml")
        
            Dim data As String = doc.<history>.<url>.@lastvisit
    
            For Each item As XElement In doc.<history>.<url>
                ListBox1.Items.Add(item.Value & " - " & data)
            Next
    Disclaimer: When code is given for example - it is merely a example. See my First CodeBank Submission Upgrading to the newest IE when using the Webbrowser control See my Second CodeBank SubmissionVB.NET - Recording History or changes using WebbrowserControl RichTextBox Textbox
    See my Third codebank submission VB.NET - Detecting Secure/Insecure Websites (ssl) w/ Webbrowser control See CodeBank Submission 4 A Simple Large View Calendar Control See my browser project BeffsBrowser Try my SpeedTest Project

    Unless said otherwise (e.g. From one of my projects thus, those are mostly licensed under MIT) - All Code snippets advice or otherwise that I post on this site, are expressly licensed under Creative Commons Attribution 4.0 International Please respect my copyrights.

  11. #11

    Thread Starter
    Frenzied Member jdc20181's Avatar
    Join Date
    Oct 2015
    Location
    Indiana
    Posts
    1,049

    Re: In all Honesty I don't know how to read/write XML files

    Quote Originally Posted by topshot View Post
    Many major browsers (i.e., Firefox and Chrome) use SQLite for history so it's time to learn databases.
    Oh I know I keep putting it off, its one of those I need to do it but, don't have the focus to pull it off. Figured I will eventually get there one step at a time.
    Disclaimer: When code is given for example - it is merely a example. See my First CodeBank Submission Upgrading to the newest IE when using the Webbrowser control See my Second CodeBank SubmissionVB.NET - Recording History or changes using WebbrowserControl RichTextBox Textbox
    See my Third codebank submission VB.NET - Detecting Secure/Insecure Websites (ssl) w/ Webbrowser control See CodeBank Submission 4 A Simple Large View Calendar Control See my browser project BeffsBrowser Try my SpeedTest Project

    Unless said otherwise (e.g. From one of my projects thus, those are mostly licensed under MIT) - All Code snippets advice or otherwise that I post on this site, are expressly licensed under Creative Commons Attribution 4.0 International Please respect my copyrights.

  12. #12

    Thread Starter
    Frenzied Member jdc20181's Avatar
    Join Date
    Oct 2015
    Location
    Indiana
    Posts
    1,049

    Re: In all Honesty I don't know how to read/write XML files

    Redacted due to an error ~ jdc
    Disclaimer: When code is given for example - it is merely a example. See my First CodeBank Submission Upgrading to the newest IE when using the Webbrowser control See my Second CodeBank SubmissionVB.NET - Recording History or changes using WebbrowserControl RichTextBox Textbox
    See my Third codebank submission VB.NET - Detecting Secure/Insecure Websites (ssl) w/ Webbrowser control See CodeBank Submission 4 A Simple Large View Calendar Control See my browser project BeffsBrowser Try my SpeedTest Project

    Unless said otherwise (e.g. From one of my projects thus, those are mostly licensed under MIT) - All Code snippets advice or otherwise that I post on this site, are expressly licensed under Creative Commons Attribution 4.0 International Please respect my copyrights.

  13. #13

    Thread Starter
    Frenzied Member jdc20181's Avatar
    Join Date
    Oct 2015
    Location
    Indiana
    Posts
    1,049

    Re: In all Honesty I don't know how to read/write XML files

    Oh for the love of god! The forum glitched on me - Will edit out one of those replies
    Disclaimer: When code is given for example - it is merely a example. See my First CodeBank Submission Upgrading to the newest IE when using the Webbrowser control See my Second CodeBank SubmissionVB.NET - Recording History or changes using WebbrowserControl RichTextBox Textbox
    See my Third codebank submission VB.NET - Detecting Secure/Insecure Websites (ssl) w/ Webbrowser control See CodeBank Submission 4 A Simple Large View Calendar Control See my browser project BeffsBrowser Try my SpeedTest Project

    Unless said otherwise (e.g. From one of my projects thus, those are mostly licensed under MIT) - All Code snippets advice or otherwise that I post on this site, are expressly licensed under Creative Commons Attribution 4.0 International Please respect my copyrights.

  14. #14

    Thread Starter
    Frenzied Member jdc20181's Avatar
    Join Date
    Oct 2015
    Location
    Indiana
    Posts
    1,049

    Re: In all Honesty I don't know how to read/write XML files

    Alright so, one last question, I am doing this pretty straight forward based off the example presented, I just am curious, why each time I navigate to a page it overwrites the last bit of data? I want it to ADD to the data, not overwrite/replace. I am confused on why it is occuring this way?
    Disclaimer: When code is given for example - it is merely a example. See my First CodeBank Submission Upgrading to the newest IE when using the Webbrowser control See my Second CodeBank SubmissionVB.NET - Recording History or changes using WebbrowserControl RichTextBox Textbox
    See my Third codebank submission VB.NET - Detecting Secure/Insecure Websites (ssl) w/ Webbrowser control See CodeBank Submission 4 A Simple Large View Calendar Control See my browser project BeffsBrowser Try my SpeedTest Project

    Unless said otherwise (e.g. From one of my projects thus, those are mostly licensed under MIT) - All Code snippets advice or otherwise that I post on this site, are expressly licensed under Creative Commons Attribution 4.0 International Please respect my copyrights.

  15. #15
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,008

    Re: In all Honesty I don't know how to read/write XML files

    Quote Originally Posted by jdc20181 View Post
    That actually worked better than expected. Thanks. I think what happened was everything was confusing there was a dozen different ways to do the same thing, but all with variants of the expected results. ...
    There are differences in XDocument and XElement. I like XElement because you can use literals and because of queries. See https://docs.microsoft.com/en-us/dot...ng-an-xelement

    When I started with XML I was using all of the different approaches. I am glad I settled on XElement. My advice is pick one and stick with it.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  16. #16

    Thread Starter
    Frenzied Member jdc20181's Avatar
    Join Date
    Oct 2015
    Location
    Indiana
    Posts
    1,049

    Re: In all Honesty I don't know how to read/write XML files

    Quote Originally Posted by dbasnett View Post
    There are differences in XDocument and XElement. I like XElement because you can use literals and because of queries. See https://docs.microsoft.com/en-us/dot...ng-an-xelement

    When I started with XML I was using all of the different approaches. I am glad I settled on XElement. My advice is pick one and stick with it.
    I am just having issues now with the part where it saves the entries initially, it isn't saving existing ones, rather it is overwriting them and saving only the new entry. Which is kinda confusing, I even added a create new element part, maybe unneccessary but still trouble shooting to try and fix it. (I already closed the project and going to be going soon so I will post the code later)

    I did something like dim xelement blah blah = new xelement (<url> %ctype.control.url.string%</url>) I will post my full code later, as I was trying to avoid asking for much more help but, this one has got me stumped.
    Disclaimer: When code is given for example - it is merely a example. See my First CodeBank Submission Upgrading to the newest IE when using the Webbrowser control See my Second CodeBank SubmissionVB.NET - Recording History or changes using WebbrowserControl RichTextBox Textbox
    See my Third codebank submission VB.NET - Detecting Secure/Insecure Websites (ssl) w/ Webbrowser control See CodeBank Submission 4 A Simple Large View Calendar Control See my browser project BeffsBrowser Try my SpeedTest Project

    Unless said otherwise (e.g. From one of my projects thus, those are mostly licensed under MIT) - All Code snippets advice or otherwise that I post on this site, are expressly licensed under Creative Commons Attribution 4.0 International Please respect my copyrights.

  17. #17
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,008

    Re: In all Honesty I don't know how to read/write XML files

    XML, imho, is easier with examples. Here is a class that encapsulates some basic functionality

    Code:
    Public Class BrowsingHistoryWeb
    
        Private _HistFilePath As String 'path to history file
        Private Shared ReadOnly rootProto As XElement = <history></history>
        Private Shared ReadOnly urlProto As XElement = <url lastvisit=""></url>
        Private _hist As XElement
    
        Public Sub New(HistFilePath As String)
            Me._HistFilePath = HistFilePath
            If Not IO.File.Exists(Me._HistFilePath) Then
                Me._hist = New XElement(rootProto)
            Else
                Me._hist = XElement.Load(Me._HistFilePath)
            End If
        End Sub
    
        Public Sub SaveHist()
            Me._hist.Save(Me._HistFilePath)
        End Sub
    
        ''' <summary>
        ''' add / update a url
        ''' </summary>
        ''' <param name="URL">the url</param>
        ''' <param name="LastVisit">if not specified use DateTime.Now </param>
        ''' <remarks></remarks>
        Public Sub AddHist(URL As String, Optional LastVisit As DateTime = Nothing)
            Dim lv As String
            If LastVisit = DateTime.MinValue Then
                lv = DateTime.Now.ToString
            Else
                lv = LastVisit.ToString
            End If
    
            Dim qry As IEnumerable(Of XElement)
            qry = From u In Me._hist.Elements
                    Where u.Value = URL
                    Select u Take 1
    
            If qry.Count = 1 Then
                qry(0).@lastvisit = lv
            Else
                Dim foo As New XElement(urlProto)
                foo.Value = URL
                foo.@lastvisit = lv
                Me._hist.Add(foo)
            End If
    
        End Sub
    
        Public Function GetURLs(Optional InTheLast As TimeSpan = Nothing) As List(Of String)
            Dim rv As List(Of String)
            If InTheLast.Ticks = 0L Then
                'return all
                rv = (From u In Me._hist.Elements
                        Select u.Value).ToList
            Else
                'return urls visited in the last ??? specified by InTheLast
                Dim dt As DateTime = DateTime.Now.AddTicks(-InTheLast.Ticks)
                rv = (From u In Me._hist.Elements
                        Let ud As DateTime = DateTime.Parse(u.@lastvisit)
                        Where ud >= dt
                        Select u.Value).ToList
            End If
            Return rv
        End Function
    End Class
    To test it
    Code:
            Dim smplSites As New List(Of String)
            smplSites.Add("http://www.vbforums.com/forumdisplay.php?25-Visual-Basic-NET")
            smplSites.Add("https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=vbgeneral")
            smplSites.Add("")
            smplSites.Add("")
            smplSites.Add("https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement?view=netframework-4.7.2")
            smplSites.Add("https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/xml/embedded-expressions-in-xml")
            smplSites.Add("https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/xml/xml-literals-overview")
    
            Dim histPath As String = "c:\foo.xml" '<<<<<<<<<<<<<<<<<<<<<<<<<<
            Dim hist As New BrowsingHistoryWeb(histPath)
    
            'save the sample sites
            For Each Site As String In smplSites
                ' XML literals and embedded expressions are the last two sites
                If Site <> "" Then
                    hist.AddHist(Site)
                    hist.AddHist(Site) 'checks that update works
                End If
            Next
            smplSites = hist.GetURLs
            smplSites = hist.GetURLs(New TimeSpan(0, 0, 30, 0, 0)) 'last 30 minutes
    
            ' hist.SaveHist ' SAVE <<<<<<<<<<<<<<<<<<
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  18. #18

    Thread Starter
    Frenzied Member jdc20181's Avatar
    Join Date
    Oct 2015
    Location
    Indiana
    Posts
    1,049

    Re: In all Honesty I don't know how to read/write XML files

    I attempted to just create a new element, and add it to the document - I kinda wanna be straight forward and not have a bunch of hassle with classes and such.

    This unfotunately just did the same thing as the original sample code given, which basically overwrites the existing for the new. so it ends up being one line. I simply want to try and not have that happen...without having to use more effort than its worth.


    Code:
            Dim histpath As String = "HistoryStorage.xml"
            Dim histload As XDocument = XDocument.Load(histpath)
            Dim hist As XElement
    hist = <history>
    </history>
      Dim aHist As  XElement = New XElement(<url>CType(TabControl1.SelectedTab.Controls.Item(0), GeckoWebBrowser).Url.ToString()</url>)
            aHist.@lastvisit = DateTime.Now.ToString
            hist.Add(aHist)
    Disclaimer: When code is given for example - it is merely a example. See my First CodeBank Submission Upgrading to the newest IE when using the Webbrowser control See my Second CodeBank SubmissionVB.NET - Recording History or changes using WebbrowserControl RichTextBox Textbox
    See my Third codebank submission VB.NET - Detecting Secure/Insecure Websites (ssl) w/ Webbrowser control See CodeBank Submission 4 A Simple Large View Calendar Control See my browser project BeffsBrowser Try my SpeedTest Project

    Unless said otherwise (e.g. From one of my projects thus, those are mostly licensed under MIT) - All Code snippets advice or otherwise that I post on this site, are expressly licensed under Creative Commons Attribution 4.0 International Please respect my copyrights.

  19. #19
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,008

    Re: In all Honesty I don't know how to read/write XML files

    Quote Originally Posted by jdc20181 View Post
    I attempted to just create a new element, and add it to the document - I kinda wanna be straight forward and not have a bunch of hassle with classes and such...
    You could have just copied and pasted the class I gave you and stepped through the code. Sorry I couldn't help.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  20. #20
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,421

    Re: In all Honesty I don't know how to read/write XML files

    Who uses XML nowadays anyway, if i were you i would skip straight past XML and learn JSON it's what all the cool kids are doing!!!
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  21. #21
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,008

    Re: In all Honesty I don't know how to read/write XML files

    Quote Originally Posted by NeedSomeAnswers View Post
    Who uses XML nowadays anyway, if i were you i would skip straight past XML and learn JSON it's what all the cool kids are doing!!!
    Unless you work somewhere that doesn't allow third party libraries.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  22. #22
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,580

    Re: In all Honesty I don't know how to read/write XML files

    Eh, let's talk about this.

    What you want is "a persistence format". The only time you care if it's JSON, XML, YAML, CSV, etc. is if you have a customer with a specific need. If it's for yourself, the right format is "whatever is convenient".

    Usually all you want to do is "save this list of things" or "load a list of things". If you can make your problem look like this case, you always have the least code to write. In these cases, file format doesn't matter and you can be served by filling in the blanks and implementing a Save() and Load().

    Next-hardest is "I want to be able to search and filter, or load things one at a time". Don't make that a requirement if you don't need it. This is still somewhat easy to do with structured file formats like XML, but you're really starting to ask for a database here.

    .NET has the best XML parsers of any programming language, and they're still confusing. XML is a very confusing format because it was meant to be a "one size fits all" solution for extremely complicated enterprise scenarios like, "I want to write a robot that can write programs that use my XML". So I don't think it's always a good idea to get down to the nuts and bolts and insert it yourself. If you do, you have to understand what each of the 3 .NET XML parsers exists for:
    • There is a "firehose" style parser in XmlTextReader and writer in XmlTextWriter that is designed for situations where the files are very large and you can't afford to keep the whole thing in memory. This is also known as "when you should be using a database."
    • XmlDocument is a "DOM parser". That means it builds a model of the XML document in memory that you can edit and query.
    • XDocument is a newer DOM parser designed to work with LINQ.
    • XmlSerializer is designed to be an easy way to read/write objects, sort of like how VB6 treated "records".

    Life is easiest if you can use XmlSerializer. If you need to use a DOM parser, it really comes down to personal preference which one you use. And the "firehose" parser is a last resort, when you need to parse something stupid like a 400MB file for a customer or serialize some object graph into an XML structure that shouldn't exist.

    This thread isn't teaching you much because instead of talking about how they work, you're getting code snippets and left to go figure it out for yourself. Let's focus on the XDocument style parser and do a bit of a dive. I don't really like the literal syntax, and I think it's nicer to learn it after you have a grasp of what not using it is like.

    First, let's talk about our data. What kind of data are we saving? Let's make a simple data class for an address book. Why start with a class? It is easiest to talk about our files if we know what our data looks like. So start a new project and add this:
    Code:
    Public Class Contact
    
        Public Property Id As Integer
        Public Property Name As String
    
    End Class
    Yes, there are more relevant properties in a useful address book. Let's keep it simple. This is "a person". I went ahead and added an ID so we can tell two different people with the same name apart, and so we can look at loading/saving integers from XML.

    The best way to write this kind of code is to start with a "bad" implementation, then start working your way back to a "good" one. I'm going to start by hard-coding values, then take baby steps to show you how to modify it into "good" serialization code that does what (I think) you want.

    Before we can use the XDocument class, let's talk a little about this API. It tries to represent all of the features of an XML file with neat little classes that are easy to create and nest, just like XML. So a document is an XDocument. An element is an XElement. They can have XAttributes. We can create a document from scratch using just these classes and manually adding data. Let's go ahead and see what happens if we do that:
    Code:
    Public Sub CreateXml()
        Dim firstContact As New XElement(
            "Contact",
            New XElement("Id", 0),
            New XElement("Name", "Celestia")
        )
    
        Dim contacts As New XElement("Contacts", firstContact)
    
        Dim document As New XDocument(contacts)
        document.Save("test.xml")
    End Sub
    I like to do it backwards and start with the data, then construct the things that hold it, then construct the document. As we investigate the API, I think you'll agree that makes sense. Each type in this API has several constructors, and some of them take other API types. That's what's going on in the creation of firstContact: it is an XElement named "Contact" that contains 2 other XElements. The code creates customer, an XElement named "Contacts" that contains firstContact. Then it creates document, an XDocument that contains the element customer. Then, we save that document. If you call this method, then peek at the output, you see this:
    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <Contacts>
      <Contact>
        <Id>0</Id>
        <Name>Celestia</Name>
      </Contact>
    </Contacts>
    See how the file structure looks like the code structure? The file contains a Contacts element, which contains a Contact element, which contains Id and Name elements. We can add a second customer:
    Code:
    Public Sub CreateXml()
        Dim firstContact As New XElement(
            "Contact",
            New XElement("Id", 0),
            New XElement("Name", "Celestia")
        )
    
        Dim secondContact As New XElement(
            "Contact",
            New XElement("Id", 1),
            New XElement("Name", "Luna")
        )
    
        Dim contacts As New XElement("Contacts", firstContact, secondContact)
    
        Dim document As New XDocument(contacts)
        document.Save("test.xml")
    End Sub
    This could get tedious, so it'd be nice to have a helper method for creating customer elements:
    Code:
    Public Sub CreateXml()
        Dim firstContact = CreateContactElement(0, "Celestia")
        Dim secondContact = CreateContactElement(1, "Luna")
    
        Dim customers As New XElement("Contacts", firstContact, secondContact)
    
        Dim document As New XDocument(customers)
        document.Save("test.xml")
    End Sub
    
    Private Function CreateContactElement(ByVal id As Integer, ByVal name As String) As XElement
        Return New XElement(
            "Contact",
            New XElement("Id", id),
            New XElement("Name", name)
        )
    End Function
    Obviously, we're intending to save Contact objects, but it can help to hand-write the data until you get both reading and writing working. We can write the data, how about reading it?

    The XDocument and XElement types can contain other elements. So they have an Element() and Elements() member that allows you to look for them. The difference between the two is if they expect one or more. There are other methods for mucking with Attributes and other features of XML, but you can read about them in the documentation.

    So reading a file is the opposite of writing it. We have to load the file contents into an XDocument, then start asking that XDocument about its elements, and those elements about their elements, all the while building up data. Here's a method that can load the XML file we wrote above and print it:
    Code:
    Public Sub PrintXmlData(ByVal filePath As String)
        ' Load the entire document into an XDocument.
        Dim document = XDocument.Load(filePath)
        ' Find the <Contacts> element.
        Dim contactsElement = document.Element("Contacts")
        ' Find every <Contact> element inside that <Contacts> element.
        Dim allContactElements = contactsElement.Elements("Contact")
    
        Dim results As New List(Of Contact)()
        For Each contactElement In allContactElements
            ' Print the contact information.
            Console.WriteLine("Customer:")
    
            ' "Get the Id element's value and convert it to an Integer"
            Dim id = Integer.Parse(contactElement.Element("Id").Value)
            Console.WriteLine("  Id: {0}", id)
    
            ' "Get the Name element's value."
            Dim name = contactElement.Element("Name").Value
            Console.WriteLine("  Name: {0}", name)
        Next
    End Sub
    It loads the XML from the file. Then it finds the <Contacts> element. Then it gets all of the <Contact> elements inside of that, and uses their <Id> and <Name> elements to print data. If you run this, you should see:
    Code:
    Customer:
      Id: 0
      Name: Celestia
    Customer:
      Id: 1
      Name: Luna
    Now you know how to read and write XML. It seems like you'd like to write a program that can load some XML, add some things to it, then save that back? The best way to do that is a direction my code is already going. If your "write XML" code can write a list, then it's a simple matter of loading the list from the file, manipulating the list, then writing the list back. Here is a fuller example using the Contact class we've been working with:
    Code:
    Imports System.IO
    
    Module Program
        Sub Main(args As String())
            Dim celestia As New Contact() With {
                .Id = 0,
                .Name = "Celestia"
            }
            Dim luna As New Contact() With {
                .Id = 1,
                .Name = "Luna"
            }
    
            If Not File.Exists("test.xml") Then
                CreateXml({celestia, luna})
            End If
    
            Dim currentContacts = LoadXml("test.xml")
            Console.WriteLine("There are currently {0} contacts.", currentContacts.Count)
    
            Console.WriteLine("Type the name of a new contact:")
            Dim newName = Console.ReadLine()
            Dim nextId = currentContacts.Last().Id + 1
            currentContacts.Add(New Contact() With {.Id = nextId, .Name = newName})
    
            CreateXml(currentContacts.ToArray())
        End Sub
    
        Public Sub CreateXml(ByVal contacts() As Contact)
            ' Create a list of <Contact> elements.
            Dim contactElements = New List(Of XElement)()
            For Each contact In contacts
                ' Add a <Contact> element for each contact in the input.
                Dim contactElement = CreateContactElement(contact)
                contactElements.Add(contactElement)
            Next
    
            ' Add the elements to a <Contact> element, then add that to a document.
            Dim contactsElement = New XElement("Contacts", contactElements)
            Dim document As New XDocument(contactsElement)
            document.Save("test.xml")
        End Sub
    
        Private Function CreateContactElement(ByVal contact As Contact) As XElement
            Return New XElement(
                "Contact",
                New XElement("Id", contact.Id),
                New XElement("Name", contact.Name)
            )
        End Function
    
        Public Function LoadXml(ByVal filepath As String) As List(Of Contact)
            ' Load the entire document into an XDocument.
            Dim document = XDocument.Load(filepath)
            ' Find the <Contacts> element.
            Dim contactsElement = document.Element("Contacts")
            ' Find every <Contact> element inside that <Contacts> element.
            Dim allContactElements = contactsElement.Elements("Contact")
    
            Dim results As New List(Of Contact)()
            For Each contactElement In allContactElements
                ' Convert the element to a Contact.
                Dim contact As New Contact()
                ' "Get the Id element's value and convert it to an Integer"
                contact.Id = Integer.Parse(contactElement.Element("Id").Value)
                ' "Get the Name element's value."
                contact.Name = contactElement.Element("Name")
                results.Add(contact)
            Next
    
            Return results
        End Function
    End Module
    It starts by checking if the file it uses exists. If not, it creates some initial data. After that check/creation, it loads data from the XML file as a List(Of Contact). Then, it asks you for the name of a contact it will add to the file. After it adds the contact to the list, it writes the list to the file. Every time you load the program, you should see the number of items in the file go up.

    Is it a lot of work? Somewhat, yes. This is why we prefer it if we can use XmlSerializer with our types, but that can introduce limitations some people don't like working around. I like to treat my persistence like it always meets this interface:
    Code:
    Public Interface IPersistence(Of Something)
    
        Function Load(ByVal input As Stream) As List(Of Something)
        Function SaveTo(ByVal input As List(Of Something), ByVal output As Stream)
    
    End Interface
    The deeper you hide the ugly bits, the prettier your code will be.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  23. #23
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,421

    Re: In all Honesty I don't know how to read/write XML files

    Unless you work somewhere that doesn't allow third party libraries.
    Json is a format not a library same as XML.
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  24. #24
    Fanatic Member
    Join Date
    Dec 2014
    Location
    VB6 dinosaur land
    Posts
    815

    Re: In all Honesty I don't know how to read/write XML files

    Quote Originally Posted by NeedSomeAnswers View Post
    Json is a format not a library same as XML.
    I believe he is inferring that most people would use Newtonsoft.Json.dll, which is not from Microsoft, rather than roll their own.

  25. #25
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,008

    Re: In all Honesty I don't know how to read/write XML files

    Quote Originally Posted by topshot View Post
    I believe he is inferring that most people would use Newtonsoft.Json.dll, which is not from Microsoft, rather than roll their own.
    You believe correctly. We use XML extensively because Microsoft has the tools that support it.

    @needsome... - believe it or not I knew that.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  26. #26
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,421

    Re: In all Honesty I don't know how to read/write XML files

    Quote Originally Posted by dbasnett View Post
    You believe correctly. We use XML extensively because Microsoft has the tools that support it.

    @needsome... - believe it or not I knew that.
    Fair enough although there are Microsoft tools that also support Json, admittedly they aren't as quite as good as the NewtonsoftJson library but they do work pretty well still.

    I have to say the idea that MS is the sole provider of tools that you can trust is a crazy policy. MS uses a number of Third-party tools inside some of its products because they are better than what they had built themselves.
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  27. #27
    Fanatic Member
    Join Date
    Dec 2014
    Location
    VB6 dinosaur land
    Posts
    815

    Re: In all Honesty I don't know how to read/write XML files

    Quote Originally Posted by NeedSomeAnswers View Post
    I have to say the idea that MS is the sole provider of tools that you can trust is a crazy policy.
    You need to read Dilbert more. Companies do crazy stuff all the time. It's amazing some survive despite themselves.

  28. #28
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,008

    Re: In all Honesty I don't know how to read/write XML files

    Quote Originally Posted by NeedSomeAnswers View Post
    Fair enough although there are Microsoft tools that also support Json, admittedly they aren't as quite as good as the NewtonsoftJson library but they do work pretty well still.

    I have to say the idea that MS is the sole provider of tools that you can trust is a crazy policy. MS uses a number of Third-party tools inside some of its products because they are better than what they had built themselves.
    The people here have been burnt. We have one system that has an application that runs on a Windows XP machine because of a third party component that is no longer supported... That system is going away by the end of the year.

    There are times I'd like to use third party controls, shareware, etc. but it is a fight I can't win.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  29. #29
    Addicted Member
    Join Date
    Nov 2011
    Posts
    161

    Re: In all Honesty I don't know how to read/write XML files

    You asked for something "pretty straight forward" and suggested you did not want something "awful in terms of amount of code", here is an example, similar to the one I was suggesting in my previous post. It is simple and should take less than 15 minutes to create, the end result is an application that reads and writes data from and to a xml file. The application can be expanded in a progressive way as you learn or require new methods and functionality.

    1./Create a new Windows Forms Application

    2./Project > Add New Item > Dataset

    3./Right click the Dataset window and Add > DataTable

    4./Right click DataTable Add > Column

    5./For this column change these properties
    AutoIncrement=True
    AutoIncrementSeed=0
    AutoIncrementStep=1
    DataType=System.Int32
    Name=ID
    ReadOnly=True
    Unique=True

    6./Right click DataTable Add > Column

    7./For this column change these properties
    Name=Name

    8./Build the project then go to View > Other Windows > Data Sources

    9./Expand the drop down at the side of DataTable1 and select Details, now drag the details onto Form1, the Navigation bar is automatically added to the form.

    10./Right click the grayed out Save icon and select Enabled.

    Now the code can be added to Form1, about seven lines makes things work.

    Code:
    Public Class Form1
    
        Private mypath As String = My.Application.Info.DirectoryPath & "\mydatabase.xml"
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            If System.IO.File.Exists(mypath) Then
                DataSet1.ReadXml(mypath)
            End If
    
        End Sub
    
    
        Private Sub DataTable1BindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles DataTable1BindingNavigatorSaveItem.Click
    
            Me.Validate()
            DataTable1BindingSource.EndEdit()
            DataSet1.WriteXml(mypath)
    
        End Sub
    
    End Class

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width


×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.