How to generate XSD from elements of XML

2020-07-05 06:04发布

问题:

I have a XML input

<field>
  <name>id</name>
  <dataType>string</dataType>
  <maxlength>42</maxlength>
  <required>false</required>
</field>

I am looking for a library or a tool which will take an XML instance document and output a corresponding XSD schema.

I am looking for some java library with which I can generate a XSD for the above XML structure

回答1:

If all you want is an XSD so that the XML you gave conforms to it, you'd be much better off by crafting it yourself rather than using a tool.

No one knows better than you the particularities of the schema, such as which valid values are there (for instance, is the <maxlength> element required? are true and false the only valid values for <required>?).

If you really want to use a tool (I'd only advice using it if you haven't designed the XML and really can't get the real XSD - or if you designed it, double check the generated XSD), you could try Trang. It can infer an XSD Schema from a number of example XML's.

You'll have to take into account that the XSD a tool can infer you might be incomplete or inaccurate if XML samples aren't representative enough.

java -jar trang.jar sampleXML.xml inferredXSD.xsd

You can find a usage example of Trang here.



回答2:

You can try with online tool called XMLGrid: http://xmlgrid.net/xml2xsd.html



回答3:

You could write an XSLT to do something like that. But the problem is, a single document alone is not enough information to generate a schema. Are any of those elements optional? Is there anything missing from that document, that might appear in other instances? How many of a particular element can there be? Do they have to be in that order? There are loads of things that can be expressed in a schema, that are not immediately obvious from one instance of a document that conforms to that schema.



回答4:

For the people who really want to include it in their Java code to generate an XSD and understand the perils, check out Generate XSD from XML programatically in Java



回答5:

Try xmlbeans it has some tools one of them is ins2xsd you can find specifics here: http://xmlbeans.apache.org/docs/2.0.0/guide/tools.html Good luck



标签: java xml xsd