【问题标题】:XML Writer stored results to string [duplicate]XML Writer将结果存储到字符串[重复]
【发布时间】:2012-11-09 17:49:04
【问题描述】:

可能重复:
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 writer 方法将所有内容存储到程序位置的 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>

【问题讨论】:

  • fillRows 是做什么的?
  • 您是否故意将格式错误的 XML 放入您的问题中?我认为这使问题变得混乱。
  • 如果您想保存一个字符串,为什么要使用 XmlWriter?发布您想要的示例。

标签: c# xml linq c#-4.0 linq-to-xml


【解决方案1】:

只需使用重载方法XmlWriter.Create(StringBuilder output) 即可创建xml 字符串。在这种情况下,所有输出都将写入StringBuilder 而不是文件:

StringBuilder builder = new StringBuilder();
XmlWriter writer = XmlWriter.Create(builder);
//... build xml here

string xml = builder.ToString();

您也可以使用XmlWriter.Create(Stream output) 将xml 写入MemoryStream

Stream stream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(stream);
// ... build xml here

stream.Position = 0;
string xml = new StreamReader(stream).ReadToEnd();

更新

下面的扩展方法将生成您的 xml 字符串。默认情况下,它使用第一列作为元素名称,但您可以为包含元数据的列传递任何列索引。另外我使用表名生成“Employees”标签,所以在创建数据表时提供名称DataTable dt = new DataTable("Employees");

public static string ToXml(this DataTable table, int metaIndex = 0)
{
    XDocument xdoc = new XDocument(
        new XElement(table.TableName,
            from column in table.Columns.Cast<DataColumn>()
            where column != table.Columns[metaIndex]
            select new XElement(column.ColumnName,
                from row in table.AsEnumerable()
                select new XElement(row.Field<string>(metaIndex), row[column])
                )
            )
        );

    return xdoc.ToString();
}

用法很简单:

string xml = dt.ToXml();

输出:

<Employees>
  <Product_Name>
    <hello1>product1</hello1>
    <hello2>product2</hello2>
    <hello3>product3</hello3>
    <hello4>product4</hello4>
  </Product_Name>
  <product_Price>
    <hello1>111</hello1>
    <hello2>222</hello2>
    <hello3>333</hello3>
    <hello4>444</hello4>
  </product_Price>
</Employees>

【讨论】:

  • 最佳方法。非常感谢。
  • @user1650470 欢迎 :) 请记住,生成的 xml 没有 xml 声明,正如您在预期输出中所希望的那样
  • 是否可以在没有表名的情况下创建 xml,即 Node here 。我尝试了几种方法,但对我不起作用。我应该如何修改扩展方法。提前致谢
  • @user1650470 实际上你需要根节点。如果您在顶层有几个不同的节点,它将不是格式良好的 xml..
  • 我现在不需要,因为我有一个函数,它接受根节点(表名)和 xml 两个参数,并从中创建一个新的 xml。
【解决方案2】:

使用StringBuildercreate the XmlWriter using the StringBuilder 代替文件:

StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb);
writer.WriteStartDocument();
//...
writer.WriteEndDocument();
var myXmlString = sb.ToString(); //myXmlString will contain the XML

【讨论】:

    【解决方案3】:

    而不是创建文件

    XmlWriter writer = XmlWriter.Create("employees.xml");
    

    你可以使用字符串流

    StringWriter sw = new StringWriter();
    XmlWriter writer = XmlWriter.Create(sw);
    ...
    ...
    // sw.ToString(); // string output
    

    【讨论】:

      猜你喜欢
      • 2020-09-20
      • 2011-06-16
      • 2015-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-06
      • 2013-03-04
      • 1970-01-01
      相关资源
      最近更新 更多