Error reading XML file in C # DataSet

I was given an XML file that I needed to read in my code as a DataSet (as a background, the file was created by creating a DataSet in C # and calling dataSet.WriteXml(file, XmlWriteMode.IgnoreSchema) , but it was done by someone else )

The .xml file has the following form:

  <?xml version="1.0" standalone="yes"?> <NewDataSet> <Foo> <Bar>abcd</Bar> <Foo>efg</Foo> </Foo> <Foo> <Bar>hijk</Bar> <Foo>lmn</Foo> </Foo> </NewDataSet> 

Using C # and .NET 2.0, I read the file using the following code:

  DataSet ds = new DataSet(); ds.ReadXml(file); 

Using a breakpoint, after that line ds.Tables[0] looked like this (using a dash instead of underscores, which I could not format correctly):

 Bar Foo-Id Foo-Id-0 abcd 0 null null 1 0 hijk 2 null null 3 2 

I found a workaround (I know there are a lot of them) and was able to successfully read in .xml, but I would like to understand why ds.ReadXml(file) is executed this way, so I can avoid the issue in the future. Thanks.

+6
c # xml
source share
2 answers

This seems correct for your nested Foo tags:

 <NewDataSet> <Foo> <!-- Foo-Id: 0 --> <Bar>abcd</Bar> <Foo>efg</Foo> <!-- Foo-Id: 1, Parent-Id: 0 --> </Foo> <Foo> <!-- Foo-Id: 2 --> <Bar>hijk</Bar> <Foo>lmn</Foo> <!-- Foo-Id: 3, Parent-Id: 2 --> </Foo> </NewDataSet> 

So, this correctly becomes 4 entries in your result with the parent-child key "Foo-Id-0"

Try:

 <NewDataSet> <Rec> <!-- Rec-Id: 0 --> <Bar>abcd</Bar> <Foo>efg</Foo> </Rec> <Rec> <!-- Rec-Id: 1 --> <Bar>hijk</Bar> <Foo>lmn</Foo> </Rec> </NewDataSet> 

This should result in:

 Bar Foo Rec-Id abcd efg 0 hijk lmn 1 
+4
source share

These are my observations, not the complete answer:

My assumption (without trying to recreate it) is that several things can happen, as the DataSet is trying to โ€œsmooth outโ€ the hierarchical structure of the relational data structure.

1) think about data in terms of a relational database; There is no obvious primary key field to identify each of the Foo elements in the collection, so the DataSet automatically used the ordinal position in the file as the automatically generated Foo-Id field.

2) Actually there are two elements called "Foo", so the strange name generation for the "Foo-Id-0" column is probably explained (it automatically generated a unique name for the column - I think you could think of it as fault tolerant behavior in the DataSet).

0
source share

All Articles