Saving XML data to an XML File from Save As Dialog

Kedhrin

Member
Joined
Jul 12, 2005
Messages
6
Hello all,

Im trying to write an XML to a file from the save as.

My program reads an XML file, loads all the values in from the Attributes in the XML file, then it needs to save it only editing the Attributes frome the specific objects in the xml, in the exact same form it was read, just with the new Attributes.

Ive been searching everywhere, and I cant find help anywhere. All sites are always talking about database editing - i am not connecting to a database in any way, I am just editing a specific type of XML file.

Every single thing works in the program except writing to a NEW xml file.

I dont want to write to the same XML file, or to a predefined "file.xml" i need it to collect the info from SaveDialog1.Filename

All the info i find on the net is all for database or to save it to a specific file pre-defined in code. I need it to get the new filename the user puts in from the save as dialog.

this is my loading the XML file and getting the attributes.


Code:
    Public Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        OpenFileDialog1.ShowDialog()
        If ShowDialog.OK Then

            TextFile.Text = OpenFileDialog1.FileName
            Dim m_xmlr As XmlTextReader
            m_xmlr = New XmlTextReader(OpenFileDialog1.FileName)
            m_xmlr.WhitespaceHandling = WhitespaceHandling.None
            m_xmlr.Read()
            m_xmlr.Read()
            m_xmlr.Read()
            m_xmlr.Read()
            m_xmlr.Read()
            While Not m_xmlr.EOF
                m_xmlr.Read()
                If Not m_xmlr.IsStartElement() Then
                    Exit While
                End If
                Dim hTop = m_xmlr.GetAttribute("hTopColor")
                Dim hBottom = m_xmlr.GetAttribute("hBottomColor")
                Dim sLight = m_xmlr.GetAttribute("dDifuse")
                Dim sDirection = m_xmlr.GetAttribute("dDirection")
                Dim fDensity = m_xmlr.GetAttribute("fDensity")
                Dim fStart = m_xmlr.GetAttribute("fStart")
                Dim fColor = m_xmlr.GetAttribute("fColor")
                Dim TopColor As String
                Dim Topstrs() As String
                TopColor = hTop
                Topstrs = TopColor.Split(",")
                Button4.BackColor = System.Drawing.Color.FromArgb(Topstrs(0), Topstrs(1), Topstrs(2))
                ColorDialog1.Color = System.Drawing.Color.FromArgb(Topstrs(0), Topstrs(1), Topstrs(2))
                Dim BottomColor As String
                Dim Bottomstrs() As String
                BottomColor = hBottom
                Bottomstrs = BottomColor.Split(",")
                Button5.BackColor = System.Drawing.Color.FromArgb(Bottomstrs(0), Bottomstrs(1), Bottomstrs(2))
                ColorDialog2.Color = System.Drawing.Color.FromArgb(Bottomstrs(0), Bottomstrs(1), Bottomstrs(2))
                Dim sColor As String
                Dim sstrs() As String
                sColor = sLight
                sstrs = sColor.Split(",")
                Button6.BackColor = System.Drawing.Color.FromArgb(sstrs(0), sstrs(1), sstrs(2))
                ColorDialog3.Color = System.Drawing.Color.FromArgb(sstrs(0), sstrs(1), sstrs(2))
                Dim Colorf As String
                Dim fstrs() As String
                Colorf = fColor
                fstrs = Colorf.Split(",")
                Button7.BackColor = System.Drawing.Color.FromArgb(fstrs(0), fstrs(1), fstrs(2))
                ColorDialog4.Color = System.Drawing.Color.FromArgb(fstrs(0), fstrs(1), fstrs(2))
                Dim sDir As String
                Dim sDirstrs() As String
                sDir = sDirection
                sDirstrs = sDir.Split(",")
                X.Text = sDirstrs(0)
                Y.Text = sDirstrs(1)
                Z.Text = sDirstrs(2)
                Density.Text = fDensity
                Start.Text = fStart
            End While
            m_xmlr.Close()
        End If
        If ShowDialog.Cancel Then
            Exit Sub
        End If
    End Sub

I need to know how to get the parsed data and put it back into the XML code into a NEW document. I have found info on this, including on the MSDN but it doesnt provide enough details ever and doesnt go into detail with examples. I am very very new to VB (Ive only been using it for 2 days), so please give me some easy-to-understand information.

Ive gotten this far into it, its a simple application, i got everything loaded, all the values changing properly etc. Now all I need to do is save it to an XML file.

if you can help me, please get back to me ASAP.

I will repost in this thread with the solution as well as a code example that lists how to do it so other people who are trying to do what I am doing might have a better chance of finding it.

THis is very BASE level xml editing, please help me :(

Id prefer a repost on here,
but you can e-mail me
contact me on aim - Kedhrin
msn - Kedhrin@yahoo.com
ICQ - 52477482
YAHOO - Kedhrin@yahoo.com

the only applications ill be writing in visual basic all detail with specific XML flies, not ever connecting to a database. I dont HAVE to do this, but it helps me out at work BIG TIME.

once I figure out how to save these files, I can probably edit future XML files without much problems.


Im using Visual Basic Express Beta.

Thank you!!!
 
First of all, i dont belive that that code is opening a file because this
Code:
OpenFileDialog1.ShowDialog()
If ShowDialog.OK Then
Is wrong.
it should be
Code:
If ( OpenFileDialog1.ShowDialog() == DialogResult.OK ) Then

Secondly, if the File i not to big, why dont you read it into a DataSet.
This has nothing to do with DataBase. A DataSet is a inmemory DataBaselike
representation of XML.

You can read and write the XML like this:
Code:
Public Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
  Dim OpenFileDialog1 as OpenFileDialog()
  OpenFileDialog1.Filter="XML-File (*.xml)|*.xml"
  
  If ( OpenFileDialog1.ShowDialog() == DialogResult.OK ) Then
    Dim myDataSet as New DataSet()
    myDataSet.ReadXml( OpenFileDialog1.FileName )

 Insert the work here    


    Dim SaveFileDialog1 as SaveFileDialog()
    SaveFileDialog1.Filter="XML-File (*.xml)|*.xml"
    If ( SaveFileDialog1.ShowDialog() == DialogResult.OK ) Then
      myDataSet.WriteXml( SaveFileDialog1.FileName )
  End If

After Reading the XML to a dataset, there will be some Tables in it.
if you could post a part of the XML it would be easy to do this
 
Thanks for the reply!

The file loading is correct, it loads perfect every time I open the load file dialog. Maybe this method is something new they put into Visual Basic Express.

I will try what you said.

Here is my xml document

please note i had to edit the actual names of the fields because I am behind an NDA, but whatever you tell me about it I can change back again to the fileds they actually are :)

[highlight=xml]
- <xml>
- <FIELD1 state1="stateofstate1">
- <TYPE1 type="type1type">
- <TYPE2Info structure1="1" structure2="1" structure3="999999" structure4="1000" structure5="1">
- <TYPE3 dur="999999">
<EDITME hTopColor="235, 170, 220" hBottomColor="80, 70, 50" dDifuse="187, 187, 243" dDirection="-0.6, -0.4, 0.6" fDensity="0.012"
fStart="-50" fColor="77,63,69" DONTTOUCHME1="250" DONTTOUCHME2="0, 0, 0" DONTTOUCHME3="0.5" DONTTOUCHME4="0.05" />
</TYPE3>
</TYPE2Info>
</TYPE1>
</FIELD1>
</xml>
[/highlight]

anyways, the areas inside EDITME are the ones im trying to edit the values of
hTopColor, hBottomColor and dDifuse are all RGB Values, i got them to load into the program, they even change the backcolor of my color changing buttons upon load, as well as the values of the ColoDialogs for each button :)

dDirection is an X Y and Z input fields, these are all parsed (look at the loading info i put and you can see how i parsed them, as well as the RGB values, since by default all the color values in VB are read as ARGB not straight RGB)

fDensity and fStart are just 2 other numeric fields i input info into.

anyways, ill try what you told me to do! I hope it works :)
 
Last edited by a moderator:
It will always open the file, even if you cancel out of the dialog - your if statement is just checking ShowDialog.Ok as a constant and not comparing it to any particular value. You should go with the code posted by FZelle.

A dataset might help you but it can result in large memory overheads and may not be the most suitable method in this case. Have you looked at the System.Xml.XmlDocument class?

Not tested the following but you would be able to load / modify and save using code similar to:
Code:
        If ( OpenFileDialog1.ShowDialog() == DialogResult.OK ) Then
            Dim x As New System.Xml.XmlDocument
            x.Load(OpenFileDialog1.FileName)
            Dim ele As Xml.XmlElement = x.GetElementById("EDITME")
            ele.Attributes("hTopColor").Value = "blah blah blah"
            x.Save("<output filename goes here>")
        End If
 
well, i got it to save the XML data to a file, but it doesnt do it when i want it to :P

basically, the way you wrote it out didnt work (must be something with visual basic express edition)

some of the classes you listed didnt exist in it.


i had to creat my save file dialog like this

Code:
            SaveFileDialog1.ShowDialog()
            If ShowDialog.OK Then
                m_xmlrDataset.WriteXml(SaveFileDialog1.FileName)
            End If

and to load my Dataset, i couldnt do a
Code:
    Dim myDataSet as New DataSet()
    myDataSet.ReadXml( OpenFileDialog1.FileName )

I had to do it like this

first, go to Project->Add Class
then i added a new DataSet to the project
it was set as DataSet1()

on the "Load" dialog, i had to declare it like this underneath the declaration of
m_xmlr
Code:
           Dim m_xmlr As XmlTextReader
            Dim m_xmlrDataset As New DataSet1()

it doesnt load the data if i press Cancel
(when i was getting the loading to work, i constantly had a feedback to a console telling me what was loaded, what wasnt, etc.)

the saving WORKS, but at the wrong time, i need it to save when i pres the save button.

right now, when you load a file it immediately pops up a box for the save dialog, you save it as whatever file, and it writes the xml back in PERFECT form.


so the saving is working,
now the questtion is, how do i get it to open the save dialog ONLY when i press the save as button. Right now i had that save dialog info
Code:
            SaveFileDialog1.ShowDialog()
            If ShowDialog.OK Then
                m_xmlrDataset.WriteXml(SaveFileDialog1.FileName)
            End If
at the bottom of the loading, so i know that is why it is loading.

when i try to put that code into the save dialog button click area, i get this error.
"Name m_xmlrDataSet is not declared"

now i know it is because it isnt declared into this Sub field,

my problem is, I dont know how to declare it and it get the what is loaded into m_xmlrDataset from the other Subs

any ideas?
 
PlausiblyDamp,

I have tried a similar example to that before

the problem comes at the last line
" x.Save("<output filename goes here>") "
and the value line " ele.Attributes("hTopColor").Value = "blah blah blah" "

I need the value to bee generated by the changes i do in the editor, not what i put in code.

the same thing with the save, since it is a Save As, it needs to be user generated not in code outputted to a file, though I might do that as a result, that would just simply cripple the pipeline and i wouldnt even bother using the app probably if it did that.
 
Couple of modifications...
Code:
If (OpenFileDialog1.ShowDialog() = DialogResult.OK) Then
    Dim x As New System.Xml.XmlDocument
    x.Load(OpenFileDialog1.FileName)
    Dim ele As Xml.XmlNodeList = x.GetElementsByTagName("EDITME")
    ele(0).Attributes("hTopColor").Value = "blah blah blah"
            
    If SaveFileDialog1.ShowDialog() =  ShowDialog.OK Then
        x.Save(SaveFileDialog1.FileName)
    End If
End If
Happily loads the file and saves it out to the specified name.
If you want to load with one button and save with another then declare the document at the form level rather than in the sub.
Ive attached a quick sample of a working version of my code. With separate Load / Save routines.
 

Attachments

Ok, that makes a lot more sense, however...

i dont understand in this line
" ele(0).Attributes("hTopColor").Value = "blah blah blah" "

when i ran something like this, it said it didnt reference to an object.

so I understand what you posted vaguley, however i need hemiTop to represent the value.

i put this in
Code:
     ele(0).Attributes("hemiTopColor").Value = hemiTop

and at the form1 base i put
Code:
    Dim hemiTop As Xml.XmlAttribute
i know im doing something wrong, at the value = part it says hemiTop cannot be used as a String. I dont really understand this (i know what a string is, and i dont know why that cant be used as a string).

Ive been trying different writes and ways of writing it and im not comming up with any luck.

basically, hemiTop will be representing the value changes, so it needs to always write to hemiTop and hemiTop will be written back in with its values assigned to it, how do ig et hemiTop to be recognized as a value holder?
 
The line
Code:
Dim ele As Xml.XmlNodeList = x.GetElementsByTagName("EDITME")
will return a list of the elements called EDITME
Code:
ele(0).Attributes("hTopColor").Value = "blah blah blah"
means take the first element, ele(0), and find the Attribute called hTopColor and set its value to the string "blah blah blah".
You dont need to create a new object to assign to the attribute - just a valid string. Ive updated my sample to change a button colour and also write out a modified file. The basics are there - you will just need to adapt them to your specific scenario
 

Attachments

It seems to me that you start programming .NET and you
have no clue what you are doing.

For ex. if you are not able to do
Code:
Dim myDataSet as New DataSet()
myDataSet.ReadXml( OpenFileDialog1.FileName )
You are probaly missing a
Code:
using System.Data;
These are basics, and if you dont know this, how do you want to master
the XML-Problem afterwords?
 
PlausiblyDamp said:
The line
Code:
Dim ele As Xml.XmlNodeList = x.GetElementsByTagName("EDITME")
will return a list of the elements called EDITME
Code:
ele(0).Attributes("hTopColor").Value = "blah blah blah"
means take the first element, ele(0), and find the Attribute called hTopColor and set its value to the string "blah blah blah".
You dont need to create a new object to assign to the attribute - just a valid string. Ive updated my sample to change a button colour and also write out a modified file. The basics are there - you will just need to adapt them to your specific scenario


Hey PlausiblyDamped thanks for the info :)

i was able to use the example you gave me, plug it in over my code and work with it and discover some new things along the way. Everything works flawlessly now.

and no Fzelle, I have no clue what im doing, like i said I had only been using VB for a day. But now i understand it a lot more and declaring things, I didnt have the time to slowly learn it, so I had to cram as much as I could in a few days.

When i get home tonight Ill post my code in example format for anyone else who has the problems im having.
 
Back
Top