benjamin54
benjamin54

Reputation: 1300

Writing XML for dataset containing multiple tables

I'm getting 2 tables in my dataset.

I need to structure my XML as:

<MyRoot>
    <Settings>
        <Param1>value1</Param1>
        <Param2>value2</Param2>
        <Param3>value3</Param3>
    </Settings>
    <Books>
      <Book>
          <BookId>1000</BookId>
          <BookName>Book1</BookName>
      </Book>
      <Book>
          <BookId>2000</BookId>
          <BookName>Book2</BookName>
      </Book>
    </Books>
</MyRoot>

But when I use datSet.WriteXML(); I'm getting XML as:

<MyRoot>
    <Settings>
        <Param1>value1</Param1>
        <Param2>value2</Param2>
        <Param3>value3</Param3>
    </Settings>
    <Book>
       <BookId>1000</BookId>
       <BookName>Book1</BookName>
    </Book>
    <Book>
       <BookId>2000</BookId>
       <BookName>Book2</BookName>
    </Book>
</MyRoot>

So, I'm not able to add separate dataset name as "Books" to second table (dataSet.Tables[1]). Is there any way that I can do that?

I tried the below code:

dataSet = GetList();
dataSet.DataSetName = "MyRoot"; 
dataSet.Tables[0].TableName = "Settings"; 
dataSet.Tables[1].TableName = "Books"; 
StringWriter swriter = new StringWriter(); 
dataSet.WriteXml(swriter); 
string dsResult = swriter.ToString();

Thanks.

Upvotes: 0

Views: 5976

Answers (2)

Milind Thakkar
Milind Thakkar

Reputation: 980

You can overwrite the original XML by some code like below.

string filename = "XmlDoc.xml";
System.IO.FileStream stream = new System.IO.FileStream (filename, System.IO.FileMode.Create);
ds.WriteXml(stream); 
XmlDocument xmldoc = new XmlDocument("XmlDoc.xml");
XmlNode node1 = xmldoc.CreateNode("Books","Books");

foreach(XmlNode nd in xmldoc.Nodes) {
  if(node.value =="Book")   
    node1.AppendChild(nd);
}

xmldoc.Nodes.Add(node1);
xmldoc.SaveAs("newXmlDoc.Xml");

Upvotes: 0

Achim
Achim

Reputation: 15702

I don't know a way to tell DataSet.WriteXml directly to write the XML in the way you want it, so you have two big options:

  • Let DataSet.WriteXml write the XML and modify it afterwards.
  • Write the serialization code yourself.

For both ways you have different options how to do it. In the first case you can

  • Load the created XML into a XDocument or XmlDocument and restructure it via code.
  • Transform your XML via XSLT (I would prefer that over the code solution)

The options in the second case should be obvious. If you create your own XmlWriter and use DataTable.WriteXml to write to it, you should be able to define your own format in a few lines of code.

To choose the right solution for your use case is up to you. I would probably go for the XSTL solution.

Upvotes: 1

Related Questions