A tool that automatically generates code to access an XML file

My application has a config xml file. This file contains more than 50 program settings. I am currently reading and saving each program separately. I think it is ineffective for such tasks .

I need something that can automatically generate code to load and save my program settings using a predefined xml schema.

I found the dataset in the Add New Item dialog. Unfortunately, I cannot add new code to dataset1, for example events in property attribute sets because of this

//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.

      

Maybe there is a tool that allows the user to create a wrapper to access the xml file? For example, DataSet1, but with the ability to add events.

Edit . I did not mark a helpful answer because I read the articles (link) you give me. I will later post a helpful answer.

+2


a source to share


8 answers


If you don't want to use app.config / web.config or a properties file (which Oded and Bruno recommends and I recommend), I highly recommend this utility:

Web Services Contract First (WSCF) blue for VS2008 and VS2010

If you are on VS2005 you will need this version of the tool: http://www.thinktecture.com/resourcearchive/tools-and-software/wscf (Don't use the VS2008 version on this site. I can never get it to work correctly.)

After installing the plugin in Visual Studio, you need the XSD schema for your XML file. ( Google for an online XSD generator .) By following the instructions on the WSCF website, you can create a wrapper class that will deserialize and reinitialize your XML and give you an abstract representation of your XML.

I suppose it is not possible (or at least very difficult) to add a new node / element TYPES, but add new instances of existing node / element types, access your data, edit the data, reorder the nodes, and then save everything back easily ...

The deserialization code looks like this:

private MyGeneratedXMLconfigClass config;
using (StreamReader sr = new StreamReader(filename))
{
   XmlSerializer cXml = new XmlSerializer(typeof(MyGeneratedXMLconfigClass));
   config = (MyGeneratedXMLconfigClass)cXml.Deserialize(sr);
}

      



Your XML has now been de-serialized into the "config" instance of your custom class. You can then access the entire class as a series of nested values ​​and lists.

For instance:

string errorFile = config.errorsFile;
List<string> actions = config.actionList;
var specialActions = from action in config.actionList
                      where action.contains("special")
                      select action;

      

Etc. etc. Then, when you're done manipulating the data, you can re-serialize this code:

using (StreamWriter wr = new StreamWriter(filename, false))
{
   XmlSerializer cXml = new XmlSerializer(typeof(MyGeneratedXMLconfigClass));
   cXml.Serialize(wr, config);
}

      

One of the very nice things about this tool is that it automatically generates all classes as "partial" classes, so you can freely extend each class yourself without fear of your code getting stomped if you ever need to regenerate because the XSD / XML has been modified.

I guess this may sound like a lot, but the learning curve is actually quite simple, and once you get it set up and running, you realize how silly easy it is. It's worth it. I swear. :-)

+2


a source


If you have a corresponding xsd schema for your xml file, microsoft provides xsd.exe with a small tool that automatically generates C # classes for that schema.



See more: http://msdn.microsoft.com/en-us/library/x6c1kb0s%28VS.71%29.aspx

+2


a source


Why are you using manual XML for configuration? What is wrong with existing app.config

and web.config

schematic?

+1


a source


Why not use . Settings file ?

+1


a source


You can follow these steps:

1) create XSD file from your XML file. Since I used to use a tool to output a schema from an XML file, I forgot what it called. I am currently using my own utility which basically runs this main program to read an XML file and generates the corresponding xsd:

static void InferSchema(string fileName)
{
    XmlWriter writer = null;
    XmlSchemaInference infer = new XmlSchemaInference();
    XmlSchemaSet sc = new XmlSchemaSet();

    string outputXsd = fileName.Replace(".xml", ".xsd");
    sc = infer.InferSchema(new XmlTextReader(fileName));

    using (writer = XmlWriter.Create(new StreamWriter(outputXsd)))   
    {
        foreach(XmlSchema schema in sc.Schemas())
        {
            schema.Write(writer);
            Console.WriteLine(">> found schema - generated to {0}", 
            outputXsd);
        }
    }
}

      

2) run xsd.exe to generate serializable class from XSD file.

xsd.exe /c /n:MyNameSpaceHere MyGenerated.xsd

      

Next, you can read the XML file into a serializable class using the XmlSerializer.Serialize () method. Something like that:

    public static void Serialize<T>(T data, TextWriter writer)
    {
        try
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            xs.Serialize(writer, data);
        }
        catch (Exception e)
        {
            throw;
        }
    }

      

Finally, you can write back to the XML file from the class using the XmlSerializer.Deserialize () method, like this:

public static void Deserialize<T>(out T data, XmlReader reader)
{
    try
    {
        XmlSerializer xs = new XmlSerializer(typeof(T));
        data = (T)xs.Deserialize(reader);
    }
    catch (Exception e)
    {
        reader.Close();
        throw;
    }
}

      

+1


a source


This is called a properties file ... C # should have something similar to the Java Properties class, where you can load all properties without hardcoding their names.

EDIT: Apparently there is no built-in parsing solution for C #. But you can easily implement your own. See here .

0


a source


Once you have an XSD file, you can create classes from this. Apart from the already mentioned xsd.exe from Microsoft (which hasn't been updated in quite a while), there are other tools for this. I am using XSD2Code , which allows for strongly typed collections, lazy initialization, etc.

If you don't have XSD, you can point xsd.exe in your XML file and it will generate XSD. The circuit usually takes some work, but is usually a good starting point.

xsd.exe (instance).xml

      

0


a source


You can use System.Xml.Serialization - it is very simple and you can even serialize class objects directly like MyCustomClass (it even keeps the public fields of MyCustomClass).

The deserializing XML file will get a new instance of MyCustomClass, so this feature is invaluable.

Note one thing: you have to add EVERY SINGLE TYPE you use in the class, but this is easy.

I have attached a complete project that does what you want. just change the classes and objects and that's it. source

for example (I am cutting the code):

using System.Xml;
using System.Xml.Serialization;
using System.IO;

[XmlRootAttribute("Vendor")]
class Vendor{
    [XmlAttribute]
    Product prod;
}
[XmlRootAttribute("Product")]
class Product{
    [XmlAttribute]
    public string name="";
}

class Test{
    Vendor v=new Vendor();
    Product p=new Product();
    p.name="a cake";
    v.prod=p;

    //add EVERY SINGLE TYPE you use in the serialized class.
    Type[] type_list = { typeof(Product) };

        XmlSerializer packer = new XmlSerializer(v.GetType(),type_list);
        XmlWriter flusher = XmlWriter.Create(@"c:\bak.xml");




        packer.Serialize(flusher, v);

        flusher.Close();

        XmlReader restorer = XmlReader.Create(@"c:\bak.xml");
        Vendor v2 = (Vendor)packer.Deserialize(restorer);

    //v2.prod.name is now "cake"
    //COOL was my first impression :P

}

      

0


a source







All Articles