![](/img/trans.png)
[英]Creating XML using DataSet.WriteXml. How to change the node name?
[英]How do you suppress the dataset name being written when using WriteXml?
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
,它將除根元素之外的所有操作轉發到實際實現。 但這確實是一種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
對象的集合, 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.