简体   繁体   English

使用 Java 从 XSD 模式生成 xml

[英]Using Java to generate xml from an XSD schema

I have a requirement to create a sort of 'skeleton' xml based on an XSD schema.我需要创建一种基于 XSD 架构的“骨架”xml。

The documents defined by these schemas have no namespace.这些模式定义的文档没有命名空间。 They are authored by other developers, not in an automated way.它们是由其他开发人员编写的,而不是自动编写的。

There is no mixed content allowed.不允许混合内容。 That is, elements can contain elements only, or text only.也就是说,元素可以只包含元素,也可以只包含文本。

The rules for this sample xml are:此示例 xml 的规则是:

  • elements that can contain only text content should not be created in the sample xml不应在示例 xml 中创建只能包含文本内容的元素
  • all other optional and mandatory elements should be included in the sample xml所有其他可选和强制性元素都应包含在示例 xml 中
  • elements should be created only once even if they can occur multiple times元素应该只创建一次,即使它们可以出现多次
  • any other nodes such as attributes, comments, processing instruction, etc. should be ommited - the sample xml would be an 'element tree'应该省略任何其他节点,例如属性、注释、处理指令等 - 示例 xml 将是一个“元素树”

Are there APIs or tools in Java that can generate such sample xml? Java 中是否有可以生成此类示例 xml 的 API 或工具? I'm looking for pointers where to get started.我正在寻找从哪里开始的指示。

This needs to be done programmatically in a reliable way, as the sample xml is used by other XSLT transformations.这需要以可靠的方式以编程方式完成,因为示例 xml 被其他 XSLT 转换使用。

Hope below code will serve your purpose希望下面的代码能达到你的目的

    package com.example.demo;
    import java.io.File;

    import javax.xml.namespace.QName;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.stream.StreamResult;

    import org.w3c.dom.Document;
    import org.w3c.dom.Element;

    import jlibs.xml.sax.XMLDocument;
    import jlibs.xml.xsd.XSInstance;
    import jlibs.xml.xsd.XSParser;

    public interface xsdtoxml {
         public static void main(String[] pArgs) {
                try {
                    String filename = "out.xsd";
                    // instance.

                    final Document doc = loadXsdDocument(filename);

                    //Find the docs root element and use it to find the targetNamespace
                    final Element rootElem = doc.getDocumentElement();
                    String targetNamespace = null;
                    if (rootElem != null && rootElem.getNodeName().equals("xs:schema")) 
                               {
                        targetNamespace = rootElem.getAttribute("targetNamespace");
                    }


                    //Parse the file into an XSModel object
                    org.apache.xerces.xs.XSModel xsModel = new XSParser().parse(filename);

                    //Define defaults for the XML generation
                    XSInstance instance = new XSInstance();
                    instance.minimumElementsGenerated = 1;
                    instance.maximumElementsGenerated = 1;
                    instance.generateDefaultAttributes = true;
                    instance.generateOptionalAttributes = true;
                    instance.maximumRecursionDepth = 0;
                    instance.generateAllChoices = true;
                    instance.showContentModel = true;
                    instance.generateOptionalElements = true;

                    //Build the sample xml doc
                    //Replace first param to XMLDoc with a file input stream to write to file
                    QName rootElement = new QName(targetNamespace, "out");
                    XMLDocument sampleXml = new XMLDocument(new StreamResult(System.out), true, 4, null);
                    instance.generate(xsModel, rootElement, sampleXml);
                } catch (TransformerConfigurationException e) 
                        {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            public static Document loadXsdDocument(String inputName) {
                final String filename = inputName;

                final DocumentBuilderFactory factory = DocumentBuilderFactory
                        .newInstance();
                factory.setValidating(false);
                factory.setIgnoringElementContentWhitespace(true);
                factory.setIgnoringComments(true);
                Document doc = null;

                try {
                    final DocumentBuilder builder = factory.newDocumentBuilder();
                    final File inputFile = new File(filename);
                    doc = builder.parse(inputFile);
                } catch (final Exception e) {
                    e.printStackTrace();
                    // throw new ContentLoadException(msg);
                }

                return doc;
            }

    }

xsd to xml : xsd 到 xml :

1 : you can use eclipse (right click and select Generate) 1:可以使用eclipse(右键选择Generate)

2 : Sun/Oracle Multi-Schema Validator 2 : Sun/Oracle 多模式验证器

3 : xmlgen 3 : xmlgen

see: How to generate sample XML documents from their DTD or XSD?请参阅: 如何从 DTD 或 XSD 生成示例 XML 文档?

for subtle requirements, you should program it yourself对于微妙的要求,您应该自己编程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM