简体   繁体   中英

How do you suppress the dataset name being written when using WriteXml?

C# - When using: DataSet.WriteXml(filePath);

The dataset name will be written as the root element. How do you suppress this?

Note: I have a schema tied to this DataSet, the XML data reads into the schema correctly.

Current Output:

<DataSet>  //dataset name prints -- REMOVE
  <HAPPY>
    <HAPPY2>BLAH</HAPPY2>
  </HAPPY>
</DataSet>  //dataset name prints  -- REMOVE

Desired Output:

  <HAPPY>
    <HAPPY2>BLAH</HAPPY2>
  </HAPPY>

An elegant solution would be to use XSLT, but that may be too much for this simple purpose. You could also implement your own custom XmlWriter which forwards every operation to a real implementation, except for the root element. But this is kind of a hack really, not the most maintainable solution.

In this simple case, I would write the XML into memory ( StringWriter + XmlWriter ), load that into an XmlDocument , and rearrange things in the DOM.

You can load the XML into memory then edit there before writing it out. How you want to write it out is up to you as removing the root node of the XML tree is going to leave you with invalid XML.

using(MemoryStream ms = new MemoryStream())
{
    dataSet.WriteXml(ms);
    ms.Position = 0;

    var children = XDocument.Load(ms).Root.Elements();
}

This code leaves you with a collection of XElement objects that represent each DataTable in your DataSet . From there you can do whatever else you need to do with it.

This works...

        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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM