Reputation: 375
I've been looking around for this for quite some time and cannot seem to get anywhere. I need to find a way to accomplisht the following two tasks, based on a .Net Entity object:
Is there anything in the Entity universe that can help do this in a simple way ?
Thx.
Upvotes: 2
Views: 7144
Reputation: 15794
I think a combination of XML serialization and schema inference is probably all that you need.
The XmlSerializer should be good enough to generate the XML file that you're looking for. You really don't need to do anything besides pass in the stream or stream writer, and the instance of the root-level entity. The actual code for XML serialization is 2 lines:
// for example:
public static void Serialize<T> (T data, TextWriter writer)
{
var xs = new XmlSerializer(typeof(T))
xs.Serialize(writer, data); // write out the xml to the stream writer...
}
I'm not sure why you want to avoid XML serialization.
In order to save the XSD relative to the set of entities, you can infer the schema from the generated XML. Schema inference is done by using the XmlSchemaInference
class in conjunction with XmlSchemaSet
.
I usually create a small schema inference utility for myself wherever I go, it looks like this:
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Nothing to do.");
return;
}
// first arg should contain the path to xml else error
Console.WriteLine("Inferring schema of: {0}", args[0]);
// default output should be xml name part + .xsd
InferSchema(args[0]);
}
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);
}
}
}
}
It doesn't get any simpler than that.
Upvotes: 2