简体   繁体   中英

Generating XML in C# ( using a class generated from XSD)

I am trying to generate an .xml file using C#. I am using a class generated from an XSD for this purpose.

To be precise I am doing some experiment with Nunit results.xsd .

I need to generate some elements multiple times. I have below code at end of each function

 var serializer = new XmlSerializer(typeof(resultType));
  using (var stream = new StreamWriter(@"C:\test.xml",true))
serializer.Serialize(stream, data);

When I execute this multiple times, I am seeing the xml tag with XML version and encoding getting appended every time.

How can I put them as a individual functions so that I can call the objects multiple times for creating multiple XML elements of same type and in the end save the XML with data? I need the generated file to have structure similar to Nunit's results XML file.

Edit; We use a "proxy" class to change the outcome without altering the existing schemes.

using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace Tool.Cons
{
class Result
{
    [XmlElement("test-suite")]
    public testsuiteType[] testsuite { get; set; }

    /// <remarks/>
    [XmlAttribute()]
    public string name { get; set; }

    /// <remarks/>
    [XmlAttribute()]
    public decimal total { get; set; }

    /// <remarks/>
    [XmlAttribute()]
    public decimal failures { get; set; }

    /// <remarks/>
    [XmlAttribute("not-run")]
    public decimal notrun { get; set; }

    /// <remarks/>
    [XmlAttribute()]
    public string date { get; set; }

    /// <remarks/>
    [XmlAttribute()]
    public string time { get; set; }
}

class Program
{
    static void AppendTestSuite(XDocument xdocument, testsuiteType suite)
    {
        var ser = new XmlSerializer(typeof(testsuiteType));
        using (var writer = xdocument.Root.CreateWriter())
        {
            // We need this for some reason...
            writer.WriteWhitespace("");
            ser.Serialize(writer, suite);
        }
    }

    static void Main(string[] args)
    {
        var res = GetTestResult();
        var xdoc = new XDocument();
        // Create the root element.
        using (var writer = xdoc.CreateWriter())           
            ser.Serialize(writer, res);

        // For testing purposes:
        AppendTestSuite(xdoc, res.testsuite);
        var _out = xdoc.ToString();
    }
}
}

You could run xsd.exe (In the Microsoft SDK folder) using the switch /c <path to xsd> to generate a strongly-typed class for you. It's perfect in quite some cases. However!! The structure that is created isn't your daily class building experience. The class is quite oddly build, so please pay attention when using it.

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