【问题标题】:How do I add extra information to XML generated from a dataset Writexml in C#?如何将额外信息添加到从 C# 中的数据集 Writexml 生成的 XML 中?
【发布时间】:2025-12-07 07:25:01
【问题描述】:
ds.WriteXml(strXmlTestCasePath, XmlWriteMode.IgnoreSchema); 

ds 是dataset。我想在这个 XML 中添加额外的一行或额外的信息。我该怎么做?

【问题讨论】:

    标签: c# .net xml dataset


    【解决方案1】:

    使用XmlWriter 写您的DataSet。然后,您可以使用相同的对象来编写其他 XML。

    示例代码:

                System.Data.DataSet ds;
                System.Xml.XmlWriter x;
                ds.WriteXml(x);
                x.WriteElementString("test", "value");
    

    【讨论】:

    • 我希望它写入相同的 xml
    • 它是对用于写入 DataSet 的 xml 和额外 xml 的同一对象的引用。
    • 实际上我的问题是我现在已经将我的数据集保存在一个 xml 中,在将它写入 xml 之后,我必须在我现在保存的 xml 中添加一个额外的行
    • 是的,他回答了你的问题。你认为他回答的哪一部分没有回答你的问题?
    • 运行此代码时,由于使用未分配的局部变量而返回错误
    【解决方案2】:

    您不能简单地将更多 XML 写入序列化的 DataSet 的末尾,因为如果这样做,您将生成一个包含多个*元素的 XML 文档。使用XmlWriter,您需要执行以下操作:

    using (XmlWriter xw = XmlWriter.Create(strXmlTestCasePath));
    {
       xw.WriteStartElement("container");
       ds.WriteXml(xw, XmlWriteMode.IgnoreSchema);
       // from here on, you can use the XmlWriter to add XML to the end; you then
       // have to wrap things up by closing the enclosing "container" element:
       ...
       xw.WriteEndElement();
    }
    

    但是,如果您尝试在序列化的DataSet 中添加 XML 元素,这将无济于事。为此,您需要序列化DataSet,将其读入XmlDocument,然后使用DOM 方法来操作XML。

    或者,或者,在序列化DataSet 之前创建并填充一个新的DataTable,然后在完成后将其删除。这真的取决于您的实际要求。

    【讨论】:

      最近更新 更多