2010-03-10 75 views
1
DataSet ds = GetExcelToXml("test.xls"); 

    string filename = @"C:\test.xml"; 

    FileStream myFileStream = new FileStream(filename, FileMode.Create); 

    XmlTextWriter myXmlWriter = new XmlTextWriter(myFileStream, Encoding.Default); 

    ds.WriteXml(myXmlWriter); 

    myXmlWriter.Close(); 

輸出XMLC#的DataSet到XML,節點重命名

<NewDataSet> 
    <Table> 
    <UserName>bla1</User_Name> 
    <Mail>[email protected]</Mail> 
    <Address>World</Address> 
    </Table> 
</NewDataSet> 

我需要XML節點名稱

<ROWS> 
     <ROW> 
     <UserName>bla1</User_Name> 
     <Mail>[email protected]</Mail> 
     <Address>World</Address> 
     </ROW> 
    </ROWS> 

如何煉成的?

回答

4

嘗試此,

ds.DataSetName = "ROWS"; 
ds.Tables[0].TableName = "ROW"; 
ds.WriteXml(myXmlWriter); 
myXmlWriter.Close(); 
1
XmlDocument myXml; 

myXml.Load(myXmlWriter); //Not sure if this will work, but you get the idea 

myXml.InnerXml = myXml.InnerXml.Replace("< NewDataSet", "< ROWS") 
    .Replace("< /NewDataSet>", "< /ROWS>") 
    .Replace("< Table", "< ROW") 
    .Replace("< /Table>", "< /ROW>"); 
0

下面是一個示例C#應用程序將讀取輸入XML,然後不同的XML /數據表複製到使用表名的其他文件:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data; 
using System.Xml; 
using System.IO; 

namespace ConsoleApplication1 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     DataSet dsXml = new DataSet(); 
     dsXml.ReadXml("mydata.xml"); 
     for (int i = 0; i < dsXml.Tables.Count; i++) 
     { 
      Console.WriteLine("Table Name: " + dsXml.Tables[i].TableName); 
      DataSet newDataSet = new DataSet(); 
      newDataSet.Tables.Add(dsXml.Tables[i].Copy()); 
      FileStream myFileStream = new FileStream(dsXml.Tables[i].TableName + ".xml", FileMode.Create); 
      XmlTextWriter myXmlWriter = new XmlTextWriter(myFileStream, Encoding.Default); 
      newDataSet.WriteXml(myXmlWriter); 
      myXmlWriter.Close(); 
     } 
    } 
} 
} 
0

如果有人來這裏尋找相反方向的問題,其中類型化數據集表名稱在寫入xml文件後發生了變化。

// for xml files created prior to rename of Sample table to SampleS, 
// rename the Sample table, read xml, 
// then rename table back to current SampleS 
if (ds.SampleS.Count == 0) 
{ 
    ds = new AnalysisDSX(); 
    ds.Tables["SampleS"].TableName = "Sample"; 
    ds.ReadXml(xmlFilePath); 
    ds.Tables["Sample"].TableName = "SampleS"; 
}