473,806 Members | 2,330 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

NewRow fails when using XML document as Dataset

Hi All,

I am using following code snippet to add another user in Users.xml:
-------------------------------------------------------------------
DataSet dstUsers = new DataSet();
dstUsers.ReadXm l("Users.xml" );
DataTable dtbUsers = dstUsers.Tables["User"];
DataRow drwUser = dtbUsers.NewRow ();
drwUser["UserName"] = "Test User 2";
dtbUsers.Rows.A dd(drwUser);
dstUsers.WriteX ml("Users.xml") ;
-------------------------------------------------------------------
Users.xml looks like
-------------------------------------------------------------------
<?xml version="1.0" standalone="yes "?>
<Configuratio n>
<Users>
<User>
<UserName>Tes t User</UserName>
</User>
</Users>
<Roles>
<Role>
<RoleName>Tes t Role</RoleName>
</Role>
</Roles>
</Configuration>
-------------------------------------------------------------------

After execution of code, <User> tag is inserted at wrong position and
Users.xml looks like:
-------------------------------------------------------------------
<?xml version="1.0" standalone="yes "?>
<Configuratio n>
<Users>
<User>
<UserName>Tes t User</UserName>
</User>
</Users>
<User>
<UserName>Tes t User 2</UserName>
</User>
<Roles>
<Role>
<RoleName>Tes t Role</RoleName>
</Role>
</Roles>
</Configuration>
-------------------------------------------------------------------

But if I modify Users.xml as below, <User> tag is inserted at proper
position.
-------------------------------------------------------------------
<?xml version="1.0" standalone="yes "?>
<Users>
<User>
<UserName>Tes t User</UserName>
</User>
</Users>
-------------------------------------------------------------------

Can anyone give any idea that how can I insert <User> tag inside
<Users> tag without modifying XML format like above???
Nov 12 '05 #1
1 2559
"Piyush Gupta" <pi*******@gmai l.com> wrote in message news:f6******** *************** ***@posting.goo gle.com...
Can anyone give any idea that how can I insert <User> tag inside
<Users> tag without modifying XML format like above???
What you probably think you're seeing when you look at
the XML fragment,

: : <Users>
<User>
<UserName>Tes t User</UserName>
</User>
</Users>
is one DataTable named "User," based on the simple
statements you've used to add a row to this table,

: : DataTable dtbUsers = dstUsers.Tables["User"];
DataRow drwUser = dtbUsers.NewRow ();
drwUser["UserName"] = "Test User 2";
dtbUsers.Rows.A dd(drwUser);
but this appearance can, perhaps, be misleading.

Actually, there are 2 DataTables in the above XML
fragment, and no less than 3 DataColumns (not one).
If you read the DataRow in dstUsers.Tables["User"]
to begin with, you'll see two of these DataColumns,
the "UserName" column and the "Users_Id" 'foreign
key' column that relates the "User" child DataTable
to it's "Users" parent DataTable.

: : <Users>
<User>
<UserName>Tes t User</UserName>
</User>
</Users>
<User>
<UserName>Tes t User 2</UserName>
</User>


The <User> record here appears outside of a <Users>
container because when adding a new DataRow you've
specified no value for the Users_Id column that
tells the DataSet which <Users> container element
that <User> record belongs to. Since it's value
for Users_Id is 'null', it appears outside of any
containing <Users> element.

The corrected code would look like this,

DataTable dtbUsers = dstUsers.Tables[ "User"];
DataRow drwUser = dtbUsers.NewRow ( );
drwUser[ "UserName"] = "Test User 2";
drwUser[ "Users_Id"] = 0; // Put under first <Users> element.
dtbUsers.Rows.A dd( drwUser);

If the XML document you're working with isn't truly a
relational data set, then using DataSet to manipulate
that document should be discouraged. You'll have a
much easier time working directly with an XmlDocument,
instead:

// Create and load XmlDocument
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load( "Users.xml" );

// Position yourself where you want to insert new elements.
XmlNode eUsers = xmlDoc.Document Element.FirstCh ild;

// Create <User>/<UserName>/#text.
XmlElement eUserNew = xmlDoc.CreateEl ement( "User");
XmlElement eUserNameNew = xmlDoc.CreateEl ement( "UserName") ;
XmlText txUserNameNew = xmlDoc.CreateTe xtNode( "Test User 2");

// Connect the XmlNodes you've just created.
eUserNameNew.Ap pendChild( txUserNameNew);
eUserNew.Append Child( eUserNameNew);
eUsers.AppendCh ild( eUserNew);

The XmlDocument will hold an open file handle when you call
Load() with the filename string, so it's usually best to
cons'up an XmlTextReader to load the file (then close the
XmlTextReader after the load operation has completed) and
use an XmlTextWriter to save the file.

However, you never have to guess what your data model is,
as when trying to shove these manipulations through the
DataSet API (which is really intended for other purposes.)
Derek Harmon
Nov 12 '05 #2

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

Similar topics

1
2106
by: CB | last post by:
Using C# in .Net 2003, DataSet.ReadXml fails when a percentage (%) sign is in the filename followed by 2 hex characters. Seems that the % sign is likely encoding the following 2 hex characters. So c:\test%ab.xml fails for ReadXml since %ab is interpreted as 171 and c:\test171.xml does not exist. There is no problem with c:\test%mn.xml because "mn" is not a hex code. If I replace the % sign with %25 (25hex = 37dec = ascii code for %),...
0
6443
by: Michelle Keys | last post by:
I am trying to call a print function to print a string from a database using javascript. Which is RC_DATA of Varchar2(2500). This is a javascript is not being used. I have a thing that needs to be modified: if(e.CommandName =="Print") { string parsedreceipt = null; parsedreceipt = DecodeReceipt (e.Item.Cells.Text); Session = parsedreceipt;
1
6432
by: ratnakarp | last post by:
Hi, I have a search text box. The user enters the value in the text box and click on enter button. In code behind on button click i'm writing the code to get the values from the database and binding it to a repeater control. This repeater control has multiple text boxes and buttons. Can you please tell me how can i do paging in this case ? I'm posting my code below. The problem is that if i click on "AdjustThisAd" button, it opens...
14
2871
by: Agnes | last post by:
I only one datagrid, and one button. the buttonwill process ' dtmyTable.newrow()' , However, the datagrid seems didn't add the row byitself ?? Thanks
5
3545
by: PAUL | last post by:
Hello, I have 2 tables with a relationship set up in the dataset with vb ..net. I add a new record to the parent table then edit an existing child record to have the new parent ID. However when I do the update the changed parentid in the child table fails to change. No error is given its just that the change is not written to the Database. When I step through the records for the child table the one I would expect to be changed has a row...
1
1408
by: mrstrong | last post by:
Gday, I have just started c# .net about 3 months ago and have recently (last week) upgraded to 2005 and hoping for some assistance understanding the best approach to adding new records to a table. The application that I am creating is a distributed application that has an Oracle DB, an XML WebService, and a Windows Forms application front end - similar to: http://msdn2.microsoft.com/en-us/library/1as0t7ff.aspx
0
1700
by: c.w.browne | last post by:
Hi, Ive had a bit of a look around for other people with this problem and cant find anything that solves it in my case, so I'm afraid im going to have to bother you all with a post of my own. Essentially, I am trying to read in an xml schema and then an xml document into a dataset using ReadXmlSchema and then ReadXml. When i do this, i end up with a table in the dataset (which i assume is created when i read the schema), but no rows...
2
996
by: ERNESTP | last post by:
Hi all, I am starting to learn how to program VB.Net and I found got an problem when try to insert a new row into the table. I had create an form to whole all the DataSet, OleDbDataAdaper and connection. Each adapter will only hold one table and one type of transaction e.g. dsADataGrid (table A use for data grid only), dsA (for select, indert, update ...), dsAMaxCC (for select the maximun value in CC column from table A) I have no...
1
1413
by: Pitmaster | last post by:
Hi there, hoping somebody can help out here. Searched half earth to find a solution but no success yet. The following code doesn't gave any fault or warning but doesn't what it is suppose to do. Can somebody explain why this code does not produce an extra new row in my database? Thanks, Nico ************************************************************************ Imports System.Data.OleDb
0
9719
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
10366
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
10371
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
10110
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...
0
9187
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6877
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
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3850
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3008
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.