473,832 Members | 2,114 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Basic XML file creation / editing

Is there a basic guide on Xml document creation and editing (simpler
than the MSDN docs). Say I want to create a file containing the
following:

<?xml version="1.0" encoding="utf-8" standalone="yes "?>
<Files>
<File>
<Text>Test</Text>
<Name>Test.html </Name>
</File>
</Files>

I know how you can use XMLTextWriter to do this:

XmlTextWriter xtw = new XmlTextWriter(" myfile.xml",
System.Text.Enc oding.UTF8);
xtw.WriteStartD ocument(true);
xtw.WriteStartE lement("Files") ;
xtw.WriteStartE lement("File");
xtw.WriteElemen tString("Text", txtName.Text);
xtw.WriteElemen tString("Name", FileName);
xtw.WriteEndEle ment();
xtw.WriteEndEle ment();
xtw.WriteEndDoc ument();
xtw.Close();

However, how do you check if the file exists, and append to it instead
of overwriting?

<?xml version="1.0" encoding="utf-8" standalone="yes "?>
<Files>
<File>
<Text>Test</Text>
<Name>Test.html </Name>
</File>
<File>
<Text>Test 2</Text>
<Name>Test2.htm l</Name>
</File>
</Files>

Also, I may wish to delete an existing entry, under certain
circumstances (file deleted from disk):

<?xml version="1.0" encoding="utf-8" standalone="yes "?>
<Files>
<File>
<Text>Test 2</Text>
<Name>Test2.htm l</Name>
</File>
</Files>

And also, prevent duplicate entries being added (re uploading a file).

<?xml version="1.0" encoding="utf-8" standalone="yes "?>
<Files>
<File>
<Text>Test</Text>
<Name>Test.html </Name>
</File>
<File>
<Text>Test 2</Text>
<Name>Test2.htm l</Name>
</File>
<File>
<Text>Test</Text>
<Name>Test.html </Name>
</File>
</Files>

I know there is a class library at the code project that writes to XML
files (http://www.codeproject.com/csharp/ReadWriteXmlIni.asp), but it
does far more than I need and I would rather learn how to do it myself
than rely on a third party library.

I would also like to read the xml from the file and then display in a
page (links to documents, Text is the link text, Name is the file
name). Bound to a repeater, also displaying file size by querying the
file system.

Nov 16 '05 #1
8 11364
Hello,
Have a look at System.Xml.XmlD ocument class in MSDN, i feel it is much
easier and flexible to use than XmlTextWriter class.
Cheers.

Maqsood Ahmed [MCP,C#]
Kolachi Advanced Technologies
http://www.kolachi.net

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #2
Is there any other guide to do this, apart from the MSDN reference?

i.e. Pseudo code:

Load file into XmlDocument.
If file does not exist, create it (with xml decleration, and root
element).
String Text = "My File"
String Name = "MyFile.txt "
SELECT <File> FROM <Files>
If RecordsFound > 0 Then
Boolean TextFound = False
For <File> in <Files>
If <Text> = Text Then TextFound = True
Next
If Not TextFound Then Add New <File> To <Files>
Add <Text> = Text
Add <File> = Name
End If

Nov 16 '05 #3
Check this out if you don't want to look at MSDN documentation then.
http://dowhileloop.com/publicjoe/cspdf/htp18.pdf
It has a log of examples for what you are trying to do.
Hope it helps.

--
in**@dowhileloo p.com
http://dowhileloop.com website development
http://publicjoe.dowhileloop.com -- C# Tutorials
"Sam Collett" <sa*********@gm ail.com> wrote in message
news:11******** *************@g 14g2000cwa.goog legroups.com...
Is there any other guide to do this, apart from the MSDN reference?

i.e. Pseudo code:

Load file into XmlDocument.
If file does not exist, create it (with xml decleration, and root
element).
String Text = "My File"
String Name = "MyFile.txt "
SELECT <File> FROM <Files>
If RecordsFound > 0 Then
Boolean TextFound = False
For <File> in <Files>
If <Text> = Text Then TextFound = True
Next
If Not TextFound Then Add New <File> To <Files>
Add <Text> = Text
Add <File> = Name
End If

Nov 16 '05 #4
Hi Sam,

An XML file can be many things, but first and foremost it is simply a format
for storing data and objects. You've been looking at it as a format for
storing data. I'd encourage you to look at it as a format for storing
objects... specifically a DataSet object.

You can create a dataset object, add a table for the data you want, and add
the columns for Text and Name like you've described. You can then add the
data rows that you want, sort it, bind it to a databound control, and have
loads of fun, all using tons of documentation online that assumes you've
retrieved the dataset from a database!

Storing it and reading it is called Serializing and Deserializing the
DataSet. (hint: think MSN Search or Google)

Nearly every operation you've described is considered to be 'basic database
operations' and is therefore completely supported with a dataset object.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
"Sam Collett" <sa*********@gm ail.com> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.com...
Is there a basic guide on Xml document creation and editing (simpler
than the MSDN docs). Say I want to create a file containing the
following:

<?xml version="1.0" encoding="utf-8" standalone="yes "?>
<Files>
<File>
<Text>Test</Text>
<Name>Test.html </Name>
</File>
</Files>

I know how you can use XMLTextWriter to do this:

XmlTextWriter xtw = new XmlTextWriter(" myfile.xml",
System.Text.Enc oding.UTF8);
xtw.WriteStartD ocument(true);
xtw.WriteStartE lement("Files") ;
xtw.WriteStartE lement("File");
xtw.WriteElemen tString("Text", txtName.Text);
xtw.WriteElemen tString("Name", FileName);
xtw.WriteEndEle ment();
xtw.WriteEndEle ment();
xtw.WriteEndDoc ument();
xtw.Close();

However, how do you check if the file exists, and append to it instead
of overwriting?

<?xml version="1.0" encoding="utf-8" standalone="yes "?>
<Files>
<File>
<Text>Test</Text>
<Name>Test.html </Name>
</File>
<File>
<Text>Test 2</Text>
<Name>Test2.htm l</Name>
</File>
</Files>

Also, I may wish to delete an existing entry, under certain
circumstances (file deleted from disk):

<?xml version="1.0" encoding="utf-8" standalone="yes "?>
<Files>
<File>
<Text>Test 2</Text>
<Name>Test2.htm l</Name>
</File>
</Files>

And also, prevent duplicate entries being added (re uploading a file).

<?xml version="1.0" encoding="utf-8" standalone="yes "?>
<Files>
<File>
<Text>Test</Text>
<Name>Test.html </Name>
</File>
<File>
<Text>Test 2</Text>
<Name>Test2.htm l</Name>
</File>
<File>
<Text>Test</Text>
<Name>Test.html </Name>
</File>
</Files>

I know there is a class library at the code project that writes to XML
files (http://www.codeproject.com/csharp/ReadWriteXmlIni.asp), but it
does far more than I need and I would rather learn how to do it myself
than rely on a third party library.

I would also like to read the xml from the file and then display in a
page (links to documents, Text is the link text, Name is the file
name). Bound to a repeater, also displaying file size by querying the
file system.

Nov 16 '05 #5
this should help
System.Xml.XmlD ocument d = new System.Xml.XmlD ocument();

if (System.IO.File .Exists("youxml .xml"))
{
d.Load("youxml. xml");
}
else
{
d.LoadXml("<fil es></files>");
}

// to add a file

System.Xml.XmlE lement fileelem = d.CreateElement ("file");

System.Xml.XmlE lement text = d.CreateElement ("Text");
text.InnerText = "some text";

System.Xml.XmlE lement name = d.CreateElement ("Name");
text.InnerText = "some name";

fileelem.Append Child(text);
fileelem.Append Child(name);

d.DocumentEleme nt.AppendChild( fileelem);

d.Save("youxml. xml");

/*
// now i'm guessing you'll want to check for dupes
// use something like this maybe

foreach(System. Xml.XmlElement elem in d.DocumentEleme nt.ChildNodes)
{
// each elem represents a <file>
}

// if found, don't append the element.
*/

"Sam Collett" <sa*********@gm ail.com> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.com...
Is there a basic guide on Xml document creation and editing (simpler
than the MSDN docs). Say I want to create a file containing the
following:

<?xml version="1.0" encoding="utf-8" standalone="yes "?>
<Files>
<File>
<Text>Test</Text>
<Name>Test.html </Name>
</File>
</Files>

I know how you can use XMLTextWriter to do this:

XmlTextWriter xtw = new XmlTextWriter(" myfile.xml",
System.Text.Enc oding.UTF8);
xtw.WriteStartD ocument(true);
xtw.WriteStartE lement("Files") ;
xtw.WriteStartE lement("File");
xtw.WriteElemen tString("Text", txtName.Text);
xtw.WriteElemen tString("Name", FileName);
xtw.WriteEndEle ment();
xtw.WriteEndEle ment();
xtw.WriteEndDoc ument();
xtw.Close();

However, how do you check if the file exists, and append to it instead
of overwriting?

<?xml version="1.0" encoding="utf-8" standalone="yes "?>
<Files>
<File>
<Text>Test</Text>
<Name>Test.html </Name>
</File>
<File>
<Text>Test 2</Text>
<Name>Test2.htm l</Name>
</File>
</Files>

Also, I may wish to delete an existing entry, under certain
circumstances (file deleted from disk):

<?xml version="1.0" encoding="utf-8" standalone="yes "?>
<Files>
<File>
<Text>Test 2</Text>
<Name>Test2.htm l</Name>
</File>
</Files>

And also, prevent duplicate entries being added (re uploading a file).

<?xml version="1.0" encoding="utf-8" standalone="yes "?>
<Files>
<File>
<Text>Test</Text>
<Name>Test.html </Name>
</File>
<File>
<Text>Test 2</Text>
<Name>Test2.htm l</Name>
</File>
<File>
<Text>Test</Text>
<Name>Test.html </Name>
</File>
</Files>

I know there is a class library at the code project that writes to XML
files (http://www.codeproject.com/csharp/ReadWriteXmlIni.asp), but it
does far more than I need and I would rather learn how to do it myself
than rely on a third party library.

I would also like to read the xml from the file and then display in a
page (links to documents, Text is the link text, Name is the file
name). Bound to a repeater, also displaying file size by querying the
file system.

Nov 16 '05 #6
Thanks.
I used ReadXml and WriteXml to get the desired effect. Removes
duplicate entries as well.

private static bool AddFile(string text, string name)
{
bool success = false;
string outfile =
Path.Combine(En vironment.GetFo lderPath(Enviro nment.SpecialFo lder.DesktopDir ectory),
"files.xml" );
DataSet ds = new DataSet("Files" );
// file table
DataTable files = new DataTable("File ");
// file columns
files.Columns.A dd("Text", typeof(string)) ;
files.Columns.A dd("Name", typeof(string)) ;
ds.Tables.Add(f iles);
try {
ds.ReadXml(outf ile);
} catch (Exception ex) {
Console.WriteLi ne(ex.Source + " : " + ex.Message);
}
DataRow[] ExistingRecords ;
ExistingRecords = files.Select("N ame = '" + name + "'");
// add if not exists
if (ExistingRecord s.Length == 0) {
DataRow NewFile;
NewFile = files.NewRow();
NewFile["Text"] = text;
NewFile["Name"] = name;
files.Rows.Add( NewFile);
} else {
// loop through existing records to find duplicates
for (int i=0; i<ExistingRecor ds.Length; i++) {
// if not the first record, delete
if (i!=0) {
ExistingRecords[i].Delete();
}
}
// change if does exist
ExistingRecords[0]["Text"] = text;
}
try {
ds.WriteXml(out file);
success = true;
} catch (Exception ex) {
Console.WriteLi ne(ex.Source + " : " + ex.Message);
//throw(ex);
}
return success;
}

Nov 16 '05 #7
Nice site you have there. Lots of good tutorials. You have more than a
books worth when you combine all free chapters from various books.

Nov 16 '05 #8
Thanks Sam, You actually should thank Mike and not me,
I am actually only hosting it for http://www.publicjoe.f9.co.uk
He was asking people for help because he doesn't have enough bandwidth at
certain months so he wants to have mirrors out there. I am more than happy
to do it for him. I actually remembered that I had been at his site a few
years back and getting some very valuable information. Who would of thought
that I would of hosted a mirror of his site. Mike is constantly writing and
posting new articles from time to time. Now that I know a lot more about
..NET I am going to help him out and write some articles for him to post on
the site.
there is also another mirror at http://publicjoe.justbe.com

--
in**@dowhileloo p.com
http://dowhileloop.com website development
http://publicjoe.dowhileloop.com -- C# Tutorials

"Sam Collett" <sa*********@gm ail.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
Nice site you have there. Lots of good tutorials. You have more than a
books worth when you combine all free chapters from various books.

Nov 16 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
7238
by: K. Shier | last post by:
when attempting to edit code in a class file, i see the bug "Visual Basic ..NET compiler is unable to recover from the following error: System Error &Hc0000005&(Visual Basic internal compiler error) Save your work and restart Visual Studio .NET." has anyone seen this bug and can you confirm one way or the other whether or not it can corrupt your source files? (by 'corrupt' i mean: do anything to it that will cause it to fail to load and...
3
2307
by: SK | last post by:
I have a file. i get the creation time using File.GetCreationTime. then i go and delete that file. and then create it again and print the File.GetCreationTime. It is giving me the old creation time itself...y is it so..?
1
1691
by: sam.collett | last post by:
Is there a basic guide on Xml document creation and editing (simpler than the MSDN docs). Say I want to create a file containing the following: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <Files> <File> <Text>Test</Text> <Name>Test.html</Name> </File>
8
12308
by: Eddie Suey | last post by:
I want to add a new line to the begining of a text file. I dont want to write over existing data. How do I do this? the file is about 7 mb.
9
2964
by: Jay Kim | last post by:
Hi, We're implementing a Windows application using Visual Basic .NET. One of the key features we need to implement is that we should be able to get the accurate byte offset of user selected text in the file. We've been trying to use the RichTextBox control to load
5
8663
by: Cameron Laird | last post by:
Question: import subprocess, StringIO input = StringIO.StringIO("abcdefgh\nabc\n") # I don't know of a compact, evocative, and # cross-platform way to exhibit this behavior. # For now, depend on cat(1). p = subprocess.Popen(, stdout = subprocess.PIPE, stdin = response)
0
1613
by: Hurricane | last post by:
I have my SQL database with a table that I am trying to have a gridview dislay with inline editing. It seems as if the dataset does not generate the apropriate update query, and therefore consequently the gridview does not automatically allow editing. I then try to change which update query that is selected being the dataRow, DataSet,dataTable or other DataRow And none of them work
1
1446
by: krithikav | last post by:
I create an excel file based on certain input from the user in ASP on the server and then display to the user after creation. Now In case the user modifies and clicks "Save" button, the modifications has to be saved back to the same file on the server. Is it possible with ASP? If so, please help me with a snippet. Krithika
6
38537
Atli
by: Atli | last post by:
This is an easy to digest 12 step guide on basics of using MySQL. It's a great refresher for those who need it and it work's great for first time MySQL users. Anyone should be able to get through this without much trouble. Programming knowledge is not required. Index What is SQL? Why MySQL? Installing MySQL. Using the MySQL command line interface
0
9642
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10780
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10498
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10540
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10212
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7753
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6951
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5789
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.