473,804 Members | 3,153 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

XML File - reading and writing

maw
Hi, could somebody point me in the right direction for adding, removing
and modifying nodes in an xml file programatically using vb.net (.net
framework 2.0)? I have an xml file in the following format which I need
to be able to add and remove records from. (I can not change this xml
file format.)

<country name="United Kingdom">
<city name="City1">
<street name="15 Street Address">
<details>
<postcode>POS COD</postcode>
<province>Count y1</province>
<c>GB</c>
</details>
</street>
</city>
<city name="City2">
<street name="10 street address">
<details>
<postcode>PST COD</postcode>
<province>Count y</province>
<c>GB</c>
</details>
</street>
</city>
</country>
I am having problems adding a node without overwriting existing data.
For example I can determine if a Country already exists in the XML file
but when I add the City and the Street items to it using the following
code, it replaces existing city and street data in the xml file rather
than appending new elements.

Sub InsertAddress(B yVal doc As XmlDocument)
Dim addresses As XmlNode = doc.DocumentEle ment
Dim country As XmlElement

If country_exists( ) Then
'append
country = doc.SelectSingl eNode("//country[@name='Country']")
Else
country = doc.CreateEleme nt("country")
country.SetAttr ibute("name", "Spain")
End If

Dim city As XmlElement = doc.CreateEleme nt("city")
city.SetAttribu te("name", "City3")

Dim street As XmlElement = doc.CreateEleme nt("street")
street.SetAttri bute("name", "20 Street Address")

Dim details As XmlElement = doc.CreateEleme nt("details")
Dim postcode As XmlElement = doc.CreateEleme nt("postcode")
postcode.InnerT ext = "POS COD"

Dim province As XmlElement = doc.CreateEleme nt("province")
province.InnerT ext = "County3"

Dim c As XmlElement = doc.CreateEleme nt("c")
c.InnerText = "UK"

country.AppendC hild(city)
city.AppendChil d(street)
street.AppendCh ild(details)
details.AppendC hild(postcode)
details.AppendC hild(province)
details.AppendC hild(c)
addresses.Appen dChild(country)
End Sub
Thanks for any help you can give.
Mark.
Jun 12 '07 #1
3 1668
RSH
You can read the XML into a dataset and allow the user to work with that,
saving the results back to XML. Loading and saving data from a dataset is
quite simple and quite effective. In my opinion it is much easier to do
this than work with the XML directly.

Public Overrides Function GetDataSet() As System.Data.Dat aSet

Dim fs As FileStream

Try

fs = New FileStream(MyBa se.FilePath, FileMode.Open)

MyBase.Dataset. ReadXml(fs)

MyBase.Dataset. Tables(0).Prima ryKey = New DataColumn()
{MyBase.Dataset .Tables(0).Colu mns(MyBase.Prim aryKey)}

Return MyBase.Dataset

Catch exc As Exception

WriteToErrorLog (exc)

Finally

fs.Flush()

fs.Close()

End Try

End Function

Public Overrides Function SaveDataset(ByV al oDs As Dataset) As Boolean

Dim fs As System.IO.Strea mWriter

Try

oDs.WriteXml(My Base.FilePath, XmlWriteMode.Wr iteSchema)

fs = New System.IO.Strea mWriter(MyBase. FilePath)

oDs.WriteXml(fs , XmlWriteMode.Wr iteSchema)

Catch exc As Exception

WriteToErrorLog (exc)

Finally

fs.Flush()

fs.Close()

End Try

End Function

End Class

Hope that helps,
Ron

"maw" <ma**@nospam.co mwrote in message
news:46******** *************** @news.zen.co.uk ...
Hi, could somebody point me in the right direction for adding, removing
and modifying nodes in an xml file programatically using vb.net (.net
framework 2.0)? I have an xml file in the following format which I need to
be able to add and remove records from. (I can not change this xml file
format.)

<country name="United Kingdom">
<city name="City1">
<street name="15 Street Address">
<details>
<postcode>POS COD</postcode>
<province>Count y1</province>
<c>GB</c>
</details>
</street>
</city>
<city name="City2">
<street name="10 street address">
<details>
<postcode>PST COD</postcode>
<province>Count y</province>
<c>GB</c>
</details>
</street>
</city>
</country>
I am having problems adding a node without overwriting existing data. For
example I can determine if a Country already exists in the XML file but
when I add the City and the Street items to it using the following code,
it replaces existing city and street data in the xml file rather than
appending new elements.

Sub InsertAddress(B yVal doc As XmlDocument)
Dim addresses As XmlNode = doc.DocumentEle ment
Dim country As XmlElement

If country_exists( ) Then
'append
country = doc.SelectSingl eNode("//country[@name='Country']")
Else
country = doc.CreateEleme nt("country")
country.SetAttr ibute("name", "Spain")
End If

Dim city As XmlElement = doc.CreateEleme nt("city")
city.SetAttribu te("name", "City3")

Dim street As XmlElement = doc.CreateEleme nt("street")
street.SetAttri bute("name", "20 Street Address")

Dim details As XmlElement = doc.CreateEleme nt("details")
Dim postcode As XmlElement = doc.CreateEleme nt("postcode")
postcode.InnerT ext = "POS COD"

Dim province As XmlElement = doc.CreateEleme nt("province")
province.InnerT ext = "County3"

Dim c As XmlElement = doc.CreateEleme nt("c")
c.InnerText = "UK"

country.AppendC hild(city)
city.AppendChil d(street)
street.AppendCh ild(details)
details.AppendC hild(postcode)
details.AppendC hild(province)
details.AppendC hild(c)
addresses.Appen dChild(country)
End Sub
Thanks for any help you can give.
Mark.

Jun 12 '07 #2
maw wrote:
I am having problems adding a node without overwriting existing data.
For example I can determine if a Country already exists in the XML file
but when I add the City and the Street items to it using the following
code, it replaces existing city and street data in the xml file rather
than appending new elements.

Sub InsertAddress(B yVal doc As XmlDocument)
Dim addresses As XmlNode = doc.DocumentEle ment
Dim country As XmlElement

If country_exists( ) Then
'append
country = doc.SelectSingl eNode("//country[@name='Country']")
Else
country = doc.CreateEleme nt("country")
country.SetAttr ibute("name", "Spain")
End If

Dim city As XmlElement = doc.CreateEleme nt("city")
city.SetAttribu te("name", "City3")

Dim street As XmlElement = doc.CreateEleme nt("street")
street.SetAttri bute("name", "20 Street Address")

Dim details As XmlElement = doc.CreateEleme nt("details")
Dim postcode As XmlElement = doc.CreateEleme nt("postcode")
postcode.InnerT ext = "POS COD"

Dim province As XmlElement = doc.CreateEleme nt("province")
province.InnerT ext = "County3"

Dim c As XmlElement = doc.CreateEleme nt("c")
c.InnerText = "UK"

country.AppendC hild(city)
city.AppendChil d(street)
street.AppendCh ild(details)
details.AppendC hild(postcode)
details.AppendC hild(province)
details.AppendC hild(c)
addresses.Appen dChild(country)
End Sub
With that code that does a lot of AppendChild calls you are only adding
new nodes but you are certainly not able to overwrite stuff that way.
So that code should work fine.
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Jun 12 '07 #3
Thanks RSH, can I still use this method with the XML file structure I
posted, i.e using attributes?

RSH wrote:
You can read the XML into a dataset and allow the user to work with that,
saving the results back to XML. Loading and saving data from a dataset is
quite simple and quite effective. In my opinion it is much easier to do
this than work with the XML directly.

Public Overrides Function GetDataSet() As System.Data.Dat aSet

Dim fs As FileStream

Try

fs = New FileStream(MyBa se.FilePath, FileMode.Open)

MyBase.Dataset. ReadXml(fs)

MyBase.Dataset. Tables(0).Prima ryKey = New DataColumn()
{MyBase.Dataset .Tables(0).Colu mns(MyBase.Prim aryKey)}

Return MyBase.Dataset

Catch exc As Exception

WriteToErrorLog (exc)

Finally

fs.Flush()

fs.Close()

End Try

End Function

Public Overrides Function SaveDataset(ByV al oDs As Dataset) As Boolean

Dim fs As System.IO.Strea mWriter

Try

oDs.WriteXml(My Base.FilePath, XmlWriteMode.Wr iteSchema)

fs = New System.IO.Strea mWriter(MyBase. FilePath)

oDs.WriteXml(fs , XmlWriteMode.Wr iteSchema)

Catch exc As Exception

WriteToErrorLog (exc)

Finally

fs.Flush()

fs.Close()

End Try

End Function

End Class

Hope that helps,
Ron

"maw" <ma**@nospam.co mwrote in message
news:46******** *************** @news.zen.co.uk ...
>Hi, could somebody point me in the right direction for adding, removing
and modifying nodes in an xml file programatically using vb.net (.net
framework 2.0)? I have an xml file in the following format which I need to
be able to add and remove records from. (I can not change this xml file
format.)

<country name="United Kingdom">
<city name="City1">
<street name="15 Street Address">
<details>
<postcode>POS COD</postcode>
<province>Count y1</province>
<c>GB</c>
</details>
</street>
</city>
<city name="City2">
<street name="10 street address">
<details>
<postcode>PST COD</postcode>
<province>Count y</province>
<c>GB</c>
</details>
</street>
</city>
</country>
I am having problems adding a node without overwriting existing data. For
example I can determine if a Country already exists in the XML file but
when I add the City and the Street items to it using the following code,
it replaces existing city and street data in the xml file rather than
appending new elements.

Sub InsertAddress(B yVal doc As XmlDocument)
Dim addresses As XmlNode = doc.DocumentEle ment
Dim country As XmlElement

If country_exists( ) Then
'append
country = doc.SelectSingl eNode("//country[@name='Country']")
Else
country = doc.CreateEleme nt("country")
country.SetAttr ibute("name", "Spain")
End If

Dim city As XmlElement = doc.CreateEleme nt("city")
city.SetAttribu te("name", "City3")

Dim street As XmlElement = doc.CreateEleme nt("street")
street.SetAttri bute("name", "20 Street Address")

Dim details As XmlElement = doc.CreateEleme nt("details")
Dim postcode As XmlElement = doc.CreateEleme nt("postcode")
postcode.InnerT ext = "POS COD"

Dim province As XmlElement = doc.CreateEleme nt("province")
province.InnerT ext = "County3"

Dim c As XmlElement = doc.CreateEleme nt("c")
c.InnerText = "UK"

country.AppendC hild(city)
city.AppendChil d(street)
street.AppendCh ild(details)
details.AppendC hild(postcode)
details.AppendC hild(province)
details.AppendC hild(c)
addresses.Appen dChild(country)
End Sub
Thanks for any help you can give.
Mark.

Jun 12 '07 #4

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

Similar topics

4
9847
by: Oliver Knoll | last post by:
According to my ANSI book, tmpfile() creates a file with wb+ mode (that is just writing, right?). How would one reopen it for reading? I got the following (which works): FILE *tmpFile = tmpfile(); /* write into tmpFile */ ...
0
3945
by: Lokkju | last post by:
I am pretty much lost here - I am trying to create a managed c++ wrapper for this dll, so that I can use it from c#/vb.net, however, it does not conform to any standard style of coding I have seen. It is almost like it is trying to implement it's own COM interfaces... below is the header, and a link to the dll+code: Zip file with header, example, and DLL:...
14
2823
by: prasadjoshi124 | last post by:
Hi All, I am writing a small tool which is supposed to fill the filesystem to a specified percent. For, that I need to read how much the file system is full in percent, like the output given by df -k lopgod10:~/mycrfile # df -k /mnt/mvdg1/vset Filesystem 1K-blocks Used Available Use% Mounted on
1
64213
AdrianH
by: AdrianH | last post by:
Assumptions I am assuming that you know or are capable of looking up the functions I am to describe here and have some remedial understanding of C programming. FYI Although I have called this article “How to Parse a File in C++”, we are actually mostly lexing a file which is the breaking down of a stream in to its component parts, disregarding the syntax that stream contains. Parsing is actually including the syntax in order to make...
13
10460
by: rohit | last post by:
Hi All, I am new to C language.I want to read integers from a text file and want to do some operation in the main program.To be more specific I need to multiply each of these integers with another set of integers stored in an array.It would be a great help if you could provide some code for it.I tried the function fscanf but by that I am able to read only the first integer of the text file.Please help me.
0
9708
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9587
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
10588
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
10340
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
10324
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
6857
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
5662
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3827
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2998
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.