You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中如何在XML内执行For循环?DataGridView写入XML遇阻

DataGridView数据写入XML的正确实现方式

问题根源

  • XML字面量无法直接嵌入循环逻辑,这是语法限制;
  • 直接字符串拼接XML会导致特殊字符被转义,因为字符串会被当作纯文本处理,而非XML节点结构。

推荐方案:使用LINQ to XML动态构建节点

这是最安全、易维护的方式,通过.NET的LINQ to XML API直接创建XML节点,自动处理语法和转义问题:

// 初始化XML文档及根节点
XDocument xmlDoc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("DataRoot")
);

XElement rootNode = xmlDoc.Element("DataRoot");

// 遍历DataGridView行数据
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    // 跳过新增的空行
    if (row.IsNewRow) continue;

    // 构建自定义节点,示例中以mydate节点为例
    XElement dataNode = new XElement("mydate",
        new XAttribute("uniqueId", row.Cells["uniqueId列名"].Value.ToString()),
        // 可添加更多子节点或属性,对应DataGridView的其他列
        new XElement("列名1", row.Cells["列名1"].Value.ToString()),
        new XElement("列名2", row.Cells["列名2"].Value.ToString())
    );

    // 将节点添加到根节点下
    rootNode.Add(dataNode);
}

// 保存XML文件
xmlDoc.Save(@"D:\output.xml");

备选方案:字符串拼接后解析为XML对象(不推荐)

如果一定要用字符串拼接,需先构建合法的XML字符串,再通过XDocument.Parse解析为XML对象后保存,避免转义问题:

StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
xmlBuilder.AppendLine("<DataRoot>");

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.IsNewRow) continue;
    string uniqueId = row.Cells["uniqueId列名"].Value.ToString();
    // 直接按XML语法拼接节点,注意属性值用双引号包裹
    xmlBuilder.AppendLine($"  <mydate uniqueId=\"{uniqueId}\" />");
}

xmlBuilder.AppendLine("</DataRoot>");

// 解析字符串为XML文档再保存
XDocument xmlDoc = XDocument.Parse(xmlBuilder.ToString());
xmlDoc.Save(@"D:\output.xml");

总结

优先选择LINQ to XML的API构建节点,无需手动处理XML语法细节,从根源避免转义错误,代码可读性和可维护性更高。

内容的提问来源于stack exchange,提问作者djsoda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 02:21:01