Skip to main content
 首页 » 编程设计

c#之XML Writer 将结果存储到字符串

2024年02月20日25lexus

<分区>

Possible Duplicate:
Alternative ways to convert data table to customized XML

DataTable dt = new DataTable(); 
dt.Columns.Add(new DataColumn("Product_ID", Type.GetType("System.String"))); 
dt.Columns.Add(new DataColumn("Product_Name", Type.GetType("System.String"))); 
dt.Columns.Add(new DataColumn("product_Price", Type.GetType("System.Int32"))); 
fillRows("hello1", dt, "product1", 1111); 
fillRows("hello2", dt, "product2", 2222); 
fillRows("hello3", dt, "product3", 3333); 
fillRows("hello4", dt, "product4", 4444); 
 
 
var xmlColumnZero = dt.AsEnumerable().Select(col => col[0].ToString()).ToArray() ; // row 0 turnovermultiplieer 
var xmlRowZero = dt.Columns; 
string firstColumnHeader = dt.Columns[0].ToString(); 
// XmlDocument xmldoc = new XmlDocument(); 
XmlWriter writer = XmlWriter.Create("employees.xml"); 
writer.WriteStartDocument(); 
writer.WriteStartElement("Employees"); 
 
// XmlElement first = xmldoc.CreateElement("Order"); 
//xmldoc.AppendChild(first); 
foreach (DataColumn dc  in dt.Columns )  
{ 
 
    if (dc.ToString() == firstColumnHeader) continue; 
    string firstcol = dc.ToString(); 
    writer.WriteStartElement(firstcol); 
    // XmlElement colRoot = xmldoc.CreateElement(firstcol); 
    //first.AppendChild(colRoot); 
    for (int i = 0 ; i <dt.Rows.Count && i< xmlColumnZero.Length ; i++) 
    { 
        string firstrow = xmlColumnZero[i]; 
        string dtagaga = dt.Rows[i][dc].ToString(); 
        writer.WriteElementString(firstrow, dtagaga); 
       // XmlElement rowRoot = xmldoc.CreateElement(firstrow, dtagaga); 
        //colRoot.AppendChild(rowRoot); 
 
 
    } 
    writer.WriteEndElement(); 
} 
writer.WriteEndElement(); 
writer.WriteEndDocument(); 

我希望在创建 XMLWriter 时将 XMl 存储到字符串中。

还有其他方法可以从表中创建 xml

XML 应该是这样的

xml 编写器方法将所有内容存储到程序位置的 xml 文件中。希望保存一个字符串

<Employees> 
<Product_Name> 
<hello1>product1</hello1> 
hello2>product2</hello2> 
hello3>product3</hello3> 
hello4>product4</hello4> 
</product_name> 
<product_Price> 
<hello1>1111</hello1> 
hello2>2222</hello2> 
hello3>3333</hello3> 
hello4>4444</hello4> 
</product_Price> 
</Employees>