Appending to xml if file found...
Appending to xml if file found...
Appending to xml if file found...
Appending to xml if file found...
Appending to xml if file found...
Appending to xml if file found... Appending to xml if file found... Appending to xml if file found... Appending to xml if file found... Appending to xml if file found... Appending to xml if file found... Appending to xml if file found... Appending to xml if file found...
Appending to xml if file found... Appending to xml if file found...
Appending to xml if file found...
Go Back  Xtreme Visual Basic Talk > > > Appending to xml if file found...


Reply
 
Thread Tools Display Modes
  #1  
Old 09-25-2010, 02:30 PM
JoePwratWork's Avatar
JoePwratWork JoePwratWork is offline
Centurion
 
Join Date: Oct 2005
Posts: 112
Default Appending to xml if file found...


I am creating an xml file if it does not exist, but am having trouble with appending to the file if it does exist. I am using the reference System.Xml Here is my code:

Code:
    Public Function App_Path() As String
        Return System.AppDomain.CurrentDomain.BaseDirectory()
    End Function

    Public Sub WriteMyFile()
        Dim aa As String
        aa = App_Path() & "\photos.xml"
        Dim writer As New XmlTextWriter(aa, System.Text.Encoding.UTF8)
        If System.IO.File.Exists(aa) = False Then
            writer.WriteStartDocument(True)
            writer.Formatting = Formatting.Indented
            writer.Indentation = 2
            writer.WriteStartElement("Photo_List")
            writer.WriteStartElement("Filename")
            writer.WriteString(txtPhotoFile.Text)
            writer.WriteEndElement()
            writer.WriteStartElement("Photo_Name")
            writer.WriteString(txtPhotoName.Text)
            writer.WriteEndElement()
            writer.WriteEndElement()
            writer.WriteEndDocument()
            writer.Close()
        Else
            ' Here is where I am having troubles.
            ' What append to xml code needs to go here?
        End If
    End Sub
Thank you,
Joe
__________________
"Chlorophyl ..more like bore a fil"
Reply With Quote
  #2  
Old 09-27-2010, 06:45 AM
JoePwratWork's Avatar
JoePwratWork JoePwratWork is offline
Centurion
 
Join Date: Oct 2005
Posts: 112
Default

Here is what I tried but it's not working.

Code:
lic Sub WriteMyFile()
        Dim aa As String
        aa = App_Path() & "\photos.xml"
        Dim writer As New XmlTextWriter(aa, System.Text.Encoding.UTF8)
        If System.IO.File.Exists(aa) = False Then
            writer.WriteStartDocument(True)
            writer.Formatting = Formatting.Indented
            writer.Indentation = 2
            writer.WriteStartElement("Photo_List")
            writer.WriteStartElement("Filename")
            writer.WriteString(txtPhotoFile.Text)
            writer.WriteEndElement()
            writer.WriteStartElement("Photo_Name")
            writer.WriteString(txtPhotoName.Text)
            writer.WriteEndElement()
            writer.WriteEndElement()
            writer.WriteEndDocument()
            writer.Close()
            MsgBox("New File")
        Else
            Dim doc As System.Xml.XmlDocument
            doc = New System.Xml.XmlDocument
            doc.Load(aa)
            writer.WriteStartElement("Photo_List")
            writer.WriteStartElement("Filename")
            writer.WriteString(txtPhotoFile.Text)
            writer.WriteEndElement()
            writer.WriteStartElement("Photo_Name")
            writer.WriteString(txtPhotoName.Text)
            writer.WriteEndElement()
            writer.Close()
            doc.Save(aa)
            MsgBox("Append File")
        End If
__________________
"Chlorophyl ..more like bore a fil"
Reply With Quote
  #3  
Old 09-27-2010, 11:12 AM
AtmaWeapon's Avatar
AtmaWeaponAppending to xml if file found... AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

You can't really append to an XML file this way due to its structure. The end of the document must close all tags that were opened before it, which means you'd need to seek backwards to find the right place in the file to write. The type of writer you are using can only write one way, so you'd have to make use of psychic powers to figure out when to start appending and it'd *still* involve some voodoo. I can envision something that would work, but it'd involve opening the file to read it, opening a temporary file to write, and caching reads before writing them in order to gain the ability to insert.

That's kind of tough and I only want to talk about doing it if you tell me your file is more than a few MB in size. The alternate technique I'm going to discuss is easier but must load the entire file into memory and build a special data structure out of it; this consumes memory faster and will perform much more slowly as the files increase in size.

The alternate technique involves using XML parsers that build a DOM tree out of the file. This means they read the entire file and build a model of it in memory that can be searched very quickly and edited easily. In .NET 4.0, you have a choice between System.Xml.XmlDocument or System.Data.Linq.XDocument. I'm less familiar with XDocument but it doesn't require you to have to fiddle with XPath so let's take it for a spin.

Let's say we've got some simple XML:
Code:
<?xml version="1.0">
<Company>
    <Employees>
        <Employee name="Bob" />
    </Employees>
    <Inventory>
        <Item>
            <Name>Gadget</Name>
            <Quantity>8</Quantity>
        </Item>
    </Inventory>
</Company>
Loading this document with XDocument is easy, so long as you remember to import System.Data.Linq/reference the DLL. (Apparently MS decided console applications wouldn't typically need to use LINQ. Strange.)
Code:
Dim document As XDocument = XDocument.Load(fileName)
Now, let's say we want to add a new employee named Alice. Here's the steps:
  1. Find the "Employees" element.
  2. Create a new "Employee" element with Alice's data.
  3. Add the new element to the children of the "Employees" element.
That's not difficult at all if you're relatively familiar with LINQ or SQL. If you're not familiar with either, you might want to brush up here and here.
Code:
Dim document As XDocument = XDocument.Load(fileName)
Dim alice As XElement = <Employee name="Alice"/>
Dim employees As XElement = (From e In document...<Employees>
                            Select e).First()
employees.Add(alice)
Note that in this and the remaining examples what looks like ellipsis ("...") is in fact an operator and should not be interpreted as meaning "fill in stuff here".

From there, saving the file is as easy as calling document.Save() and giving it the right file name.

What about if we have lots of data to add, or don't know the data at runtime? That's easy. Let's say that inventory items are stored in this class:
Code:
Class Item
    Public Property Name As String
    Public Property Quantity As Integer
End Class
Now let's say we have an array of 5 or 6 items to add all at once. No problem. We'll say we've already got the items in an array named items:
Code:
Dim newItems = From newItem In items
               Select <Item>
                          <Name><%= newItem.Name %></Name>
                          <Quantity><%= newItem.Quantity %></Quantity>
                      </Item>

Dim itemElements = (From itemElement In document...<Inventory>
                   Select itemElement).First()
itemElements.Add(newItems)

document.Save(fileName)
The <%= %> tag tells the VB compiler you want to write code within the statement; you can do some interesting stuff with it.

If you're not using VS2010, I can show you how the XmlDocument class would accomplish the same thing. If your files are larger than a few MB and this technique feels sluggish, we can explore the mess that will let you do it with the reader/writer combo.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Appending to xml if file found...
Appending to xml if file found...
Appending to xml if file found... Appending to xml if file found...
Appending to xml if file found...
Appending to xml if file found...
Appending to xml if file found... Appending to xml if file found... Appending to xml if file found... Appending to xml if file found... Appending to xml if file found... Appending to xml if file found... Appending to xml if file found...
Appending to xml if file found...
Appending to xml if file found...
 
Appending to xml if file found...
Appending to xml if file found...
 
-->