使用 WriteXml 时如何抑制正在写入的数据集名称?
How do you suppress the dataset name being written when using WriteXml?
C# - 使用时:
DataSet.WriteXml(文件路径);
数据集名称将作为根元素写入。你如何抑制它?
注意:我有一个与此数据集关联的架构,XML 数据正确读入架构。
当前输出:
<DataSet> //dataset name prints -- REMOVE
<HAPPY>
<HAPPY2>BLAH</HAPPY2>
</HAPPY>
</DataSet> //dataset name prints -- REMOVE
期望输出:
<HAPPY>
<HAPPY2>BLAH</HAPPY2>
</HAPPY>
一个优雅的解决方案是使用 XSLT,但对于这个简单的目的来说,这可能太多了。您还可以实现自己的自定义 XmlWriter
,它将每个操作转发给真正的实现,根元素除外。但这确实有点 hack,不是最可维护的解决方案。
在这个简单的例子中,我会将 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();
C# - 使用时: DataSet.WriteXml(文件路径);
数据集名称将作为根元素写入。你如何抑制它?
注意:我有一个与此数据集关联的架构,XML 数据正确读入架构。
当前输出:
<DataSet> //dataset name prints -- REMOVE
<HAPPY>
<HAPPY2>BLAH</HAPPY2>
</HAPPY>
</DataSet> //dataset name prints -- REMOVE
期望输出:
<HAPPY>
<HAPPY2>BLAH</HAPPY2>
</HAPPY>
一个优雅的解决方案是使用 XSLT,但对于这个简单的目的来说,这可能太多了。您还可以实现自己的自定义 XmlWriter
,它将每个操作转发给真正的实现,根元素除外。但这确实有点 hack,不是最可维护的解决方案。
在这个简单的例子中,我会将 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();