views:

25

answers:

2

Hello all

I want to write an XML file. I have created an XSD file named XMLSchema.xsd, and run the command 'xsd /c XMLSchema.xsd' which generated a c# class file. Now, how do I use this file to generate XML files?

Part of my code:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="XMLSchema" targetNamespace="http://tempuri.org/XMLSchema.xsd" elementFormDefault="qualified" xmlns="http://tempuri.org/XMLSchema.xsd" >
<xs:element name="root">
   <xs:complexType>
      <xs:sequence>
         <xs:element name="Audit">
            <xs:complexType>
               ...

which generates a c# class 'root'.

How do I call 'root' from my C# web program?

Thanks

+1  A: 

You need to include the root.cs file in your project, then it will be accessible.

In order to read and write XML files using this class, you need to use serialization.

Oded
A: 

As Oded said, you simply include the generated file in your project. As for loading/saving, you simply create a new XmlSerializer for your generated class, i.e. root. In code:

Loading:

using (var fileStream = File.OpenRead(xmlFilePath))
{
    using (var reader = new StreamReader(fileStream))
    {
        Root data;
        var serializer = new XmlSerializer(typeof(Root));

        try
        {
            data = serializer.Deserialize(reader) as T;
        }
        catch (InvalidOperationException exception)
        {
            // XML is invalid
            return null;
        }

        return data;
    }
}

Saving:

using (var fs = File.Create(targetPath))
{
    using (var writer = new StreamWriter(fs))
    {
        var serializer = new XmlSerializer(typeof(Root));
        serializer.Serialize(writer, value);
    }
}
Daniel Rose