如何在使用 WriteXML 时禁止写入数据集名称
本文关键字:数据集 禁止 WriteXML | 更新日期: 2023-09-27 18:36:24
C# - 使用时:DataSet.WriteXml(filePath);
数据集名称将作为根元素写入。 你如何抑制这一点?
注意:我有一个与此数据集绑定的架构,XML 数据可以正确读取到架构中。
电流输出:
<DataSet> //dataset name prints -- REMOVE
<HAPPY>
<HAPPY2>BLAH</HAPPY2>
</HAPPY>
</DataSet> //dataset name prints -- REMOVE
期望输出:
<HAPPY>
<HAPPY2>BLAH</HAPPY2>
</HAPPY>
一个优雅的解决方案是使用 XSLT,但对于这个简单的目的来说,这可能太多了。您还可以实现自己的自定义XmlWriter
,它将每个操作转发到实际实现,根元素除外。但这真的是一种黑客攻击,不是最易于维护的解决方案。
在这个简单的情况下,我会将XML写入内存(StringWriter
+ XmlWriter
),将其加载到XmlDocument
中,并在DOM中重新排列内容。
您可以将 XML 加载到内存中,然后在写出之前对其进行编辑。您希望如何写出它取决于您,因为删除 XML 树的根节点将给您留下无效的 XML。
using(MemoryStream ms = new MemoryStream())
{
dataSet.WriteXml(ms);
ms.Position = 0;
var children = XDocument.Load(ms).Root.Elements();
}
此代码为您提供了一个XElement
对象的集合,这些对象表示DataSet
中的每个DataTable
。从那里你可以做任何其他你需要做的事情。
这有效...
XmlWriter w = new XmlTextWriter("C:Blah.xml", Encoding.UTF8);
w.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
XmlDataDocument xd = new XmlDataDocument(DataSet);
XmlDataDocument xdNew = new XmlDataDocument();
DataSet.EnforceConstraints = false;
XmlNode node = xdNew.ImportNode(xd.DocumentElement.LastChild, true);
node.WriteTo(w);
w.Close();