NewRow fails when using XML document as Dataset

  • Thread starter Thread starter DotNetJunkies User
  • Start date Start date
D

DotNetJunkies User

Hi All,

I am using following code snippet to add another user in Users.xml:
-------------------------------------------------------------------
DataSet dstUsers = new DataSet();
dstUsers.ReadXml("Users.xml");
DataTable dtbUsers = dstUsers.Tables["User"];
DataRow drwUser = dtbUsers.NewRow();
drwUser["UserName"] = "Test User 2";
dtbUsers.Rows.Add(drwUser);
dstUsers.WriteXml("Users.xml");
-------------------------------------------------------------------
Users.xml looks like
-------------------------------------------------------------------
<?xml version="1.0" standalone="yes"?>
<Configuration>
<Users>
<User>
<UserName>Test User</UserName>
</User>
</Users>
<Roles>
<Role>
<RoleName>Test 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"?>
<Configuration>
<Users>
<User>
<UserName>Test User</UserName>
</User>
</Users>
<User>
<UserName>Test User 2</UserName>
</User>
<Roles>
<Role>
<RoleName>Test 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>Test User</UserName>
</User>
</Users>
 
Why don't you use XmlDocumentFragment and insert the corresponding node?

Regards,
 
It's worth looking into the DataSet to see what the XML you are loading
first is actually creating - I suspect it's more than one table. Try
outputting the value of DataSet.Tables.Count and DataSet.Table[0].TableName.
Loading XML often creates a hierarchy of related tables in order to
accomodate multiple levels of nesting in the document.
 
Back
Top