开发者

what's the best way to automate generation of an xsd given an xml sample?

开发者 https://www.devze.com 2022-12-14 22:05 出处:网络
I have a chunk of xml data that\'s coming out of a database that I need to generate an xsd for. Got it all working using xsd.exe but all the elements are showing up as string, even things like 2079.02

I have a chunk of xml data that's coming out of a database that I need to generate an xsd for. Got it all working using xsd.exe but all the elements are showing up as string, even things like 2079.0200. How do I get xsd.exe to guess at types? Would the XmlSchemaExporter class be able to do this?

The issue here is that Visual Studio is generating the xsd that I want (with decimal types etc) when I use the XML --> Create Sch开发者_如何学JAVAema command, but I don't want to have to do this by hand. I'm setting up a process that takes in a chunk of xml and generates an XSD. But it needs to have more types than just "string".

Related, but don't know if it's a solution yet (XmlSchemaInference class): Any tools to generate an XSD schema from an XML instance document?


The solution is to create the schema by hand, based on the one that's been generated. Then don't run XSD.EXE again.


John's answer is valid for situations where accuracy is more important than speed. For my situation, I needed many schemas that were identical to what would be produced via the VS "Create Schema" command. So accuracy wasn't as important as matching a known baseline and speed.

This is what I ended up doing. It produced output identical to the VS "Create Schema" command:

XmlSchemaInference inf = new XmlSchemaInference();

// xml variable on the next line is a string being passed in
XmlSchemaSet schemas = inf.InferSchema(new XmlTextReader(xml, XmlNodeType.Element, null));
schemas.Compile();

XmlSchema[] schemaArray = new XmlSchema[1];
schemas.CopyTo(schemaArray, 0);
XmlTextWriter wr = new XmlTextWriter(xsdOutputFileNameAndPath, Encoding.UTF8);
wr.Formatting = Formatting.Indented;
schemaArray[0].Write(wr);
wr.Close();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号