您好我正在使用Datable将rss转换为xml。首先,我正在阅读RSS并转换为DataTable。然后,Datatable将转换为XML。
try
{
DataTable tbl = new DataTable();
tbl.Columns.Add("id");
tbl.Columns.Add("product_name");
XmlDocument doc = new XmlDocument();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("");
XmlNodeList itemNodes = xmlDoc.SelectNodes("//rss/channel/item");
foreach (XmlNode itemNode in itemNodes)
{
DataRow row = tbl.NewRow();
XmlNode idNode = itemNode.SelectSingleNode("id");
XmlNode product_nameNode = itemNode.SelectSingleNode("product_name");
if (idNode != null && product_nameNode != null)
{
row[0] = idNode.InnerText;
row[1] = product_nameNode.InnerText;
}
tbl.Rows.Add(row);
// tbl.Rows.Add(row);
}
DataSet dataSet = new DataSet("Products");
tbl.TableName = "Product";
dataSet.Tables.Add(tbl);
// Save to disk
dataSet.WriteXml("");
dataSet.Clear();
tbl.Clear();
dataSet.Tables.Remove(tbl);
}
catch (Exception ex)
{
// Console.WriteLine(ex.Message);
// Console.Read();
}
最终的XML就像那样
<Products>
<Product>
<id>121385</id>
<product_name>ABC</product_name>
<Product>
<Product>
...
<Product>
<Product>
...
<Product>
<Products>
结果很好但我想再添加一个节点,即在
之后的totalcount<totalcount>1000</totalcount>
应该是这样的。
<Products>
<totalcount>1000</totalcount>
<Product>
...
<Product>
<Product>
...
<Product>
<Products>
如何添加totalcount元素?
答案 0 :(得分:0)
我不确定是否可以使用Custom node
方法添加WriteXml
。但您可以使用XMLWriter
并根据需要手动编写节点。
using (XmlWriter xmlWriter = XmlWriter.Create(@"\\yourfilePath.xml"))
{
xmlWriter.WriteStartElement("root");
xmlWriter.WriteStartElement("Products");
xmlWriter.WriteElementString("totalcount", dt.Rows.Count.ToString());
foreach (DataRow dataRow in dt.Rows)
{
xmlWriter.WriteStartElement("Product");
foreach (DataColumn dataColumn in dt.Columns)
{
xmlWriter.WriteElementString(dataColumn.ColumnName, dataRow[dataColumn].ToString());
}
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
}