请求指导:将读取Excel映射的Java类转换为XSD文件
Great question! Converting your Java-backed Excel field mappings into a valid XSD can be done cleanly with a structured approach. Here's a step-by-step guide tailored to your sample XSD:
1. Define a Java Model for XSD Metadata
First, create simple POJOs to represent the components of your XSD (mirroring the structure in your sample). This will let you map your existing Excel-derived data into a format that's easy to generate XSD from:
// Represents a simple type with restrictions (like type_RecordIdentifier) public class SimpleType { private String name; // e.g., "type_RecordIdentifier" private String baseType; // e.g., "xs:string" private String pattern; // e.g., "6" // Add other restrictions (enumeration, minLength) if needed } // Represents an element in a complex type sequence public class XsdElement { private String name; // e.g., "RecordIdentifier" private String type; // e.g., "type_RecordIdentifier" private String use = "required"; // default to required, adjust as needed } // Represents an attribute of a complex type public class XsdAttribute { private String name; // e.g., "id" private String type; // e.g., "type_RecordId" private String use = "required"; } // Represents a complex type (like type_Records or type_Record) public class ComplexType { private String name; private List<XsdElement> elements = new ArrayList<>(); private List<XsdAttribute> attributes = new ArrayList<>(); } // Top-level schema container public class XsdSchema { private String rootElementName = "Records"; private String rootElementType = "type_Records"; private List<ComplexType> complexTypes = new ArrayList<>(); private List<SimpleType> simpleTypes = new ArrayList<>(); }
2. Populate the Model from Your Existing Java Class
Next, map the data from your Excel-derived Java class into the XsdSchema model. For example, if your existing class has a list of field definitions with properties like fieldName, validationPattern, isAttribute, you'd loop through each field to create:
- A
SimpleTypewith the naming conventiontype_{FieldName}(matching your sample) - Either an
XsdElementorXsdAttributelinked to that simple type - Add these to the appropriate
ComplexType(e.g., all record fields go intotype_Record)
Sample mapping snippet:
// Assume your existing data is in a List<FieldMapping> fieldMappings XsdSchema schema = new XsdSchema(); // Create the type_Record complex type ComplexType recordType = new ComplexType(); recordType.setName("type_Record"); schema.getComplexTypes().add(recordType); // Add the id attribute XsdAttribute idAttr = new XsdAttribute(); idAttr.setName("id"); idAttr.setType("type_RecordId"); recordType.getAttributes().add(idAttr); // Loop through your field mappings to build elements and simple types for (FieldMapping field : fieldMappings) { // Create simple type SimpleType simpleType = new SimpleType(); simpleType.setName("type_" + field.getFieldName()); simpleType.setBaseType("xs:string"); simpleType.setPattern(field.getValidationPattern()); schema.getSimpleTypes().add(simpleType); // Create element XsdElement element = new XsdElement(); element.setName(field.getFieldName()); element.setType(simpleType.getName()); recordType.getElements().add(element); } // Don't forget to add the type_Records complex type ComplexType recordsType = new ComplexType(); recordsType.setName("type_Records"); XsdElement recordElement = new XsdElement(); recordElement.setName("Record"); recordElement.setType("type_Record"); recordsType.getElements().add(recordElement); schema.getComplexTypes().add(recordsType);
3. Generate the XSD
Choose one of two reliable methods to convert your model into an XSD file:
Option A: Use a Template Engine (Freemarker/Velocity)
This is the most straightforward approach for matching your sample's structure. Create a Freemarker template that mirrors your desired XSD:
XSD Template (xsd-template.ftl):
<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="${rootElementName}" type="${rootElementType}" /> <#list complexTypes as complexType> <xs:complexType name="${complexType.name}"> <xs:sequence> <#list complexType.elements as element> <xs:element name="${element.name}" type="${element.type}" <#if element.use == "required">use="required"</#if> /> </#list> </xs:sequence> <#if complexType.attributes?has_content> <#list complexType.attributes as attribute> <xs:attribute name="${attribute.name}" type="${attribute.type}" use="${attribute.use}" /> </#list> </#if> </xs:complexType> </#list> <#list simpleTypes as simpleType> <xs:simpleType name="${simpleType.name}"> <xs:restriction base="${simpleType.baseType}"> <#if simpleType.pattern?has_content> <xs:pattern value="${simpleType.pattern}" /> </#if> </xs:restriction> </xs:simpleType> </#list> </xs:schema>
Then process the template with your model:
// Initialize Freemarker Configuration cfg = new Configuration(Configuration.VERSION_2_3_32); cfg.setClassForTemplateLoading(YourClass.class, "/templates"); Template template = cfg.getTemplate("xsd-template.ftl"); // Write output to file try (Writer writer = new FileWriter("output.xsd")) { template.process(schema, writer); }
Option B: Use Java's DOM API
If you prefer building the XML programmatically without templates, use the standard DOM API:
// Create DOM document DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); // Create root schema element Element schemaElem = doc.createElementNS("http://www.w3.org/2001/XMLSchema", "xs:schema"); schemaElem.setAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema"); doc.appendChild(schemaElem); // Add root Records element Element rootElem = doc.createElement("xs:element"); rootElem.setAttribute("name", schema.getRootElementName()); rootElem.setAttribute("type", schema.getRootElementType()); schemaElem.appendChild(rootElem); // Add complex types for (ComplexType ct : schema.getComplexTypes()) { Element complexTypeElem = doc.createElement("xs:complexType"); complexTypeElem.setAttribute("name", ct.getName()); schemaElem.appendChild(complexTypeElem); // Add sequence Element sequenceElem = doc.createElement("xs:sequence"); complexTypeElem.appendChild(sequenceElem); // Add elements for (XsdElement elem : ct.getElements()) { Element elementElem = doc.createElement("xs:element"); elementElem.setAttribute("name", elem.getName()); elementElem.setAttribute("type", elem.getType()); if ("required".equals(elem.getUse())) { elementElem.setAttribute("use", "required"); } sequenceElem.appendChild(elementElem); } // Add attributes for (XsdAttribute attr : ct.getAttributes()) { Element attrElem = doc.createElement("xs:attribute"); attrElem.setAttribute("name", attr.getName()); attrElem.setAttribute("type", attr.getType()); attrElem.setAttribute("use", attr.getUse()); complexTypeElem.appendChild(attrElem); } } // Add simple types for (SimpleType st : schema.getSimpleTypes()) { Element simpleTypeElem = doc.createElement("xs:simpleType"); simpleTypeElem.setAttribute("name", st.getName()); schemaElem.appendChild(simpleTypeElem); Element restrictionElem = doc.createElement("xs:restriction"); restrictionElem.setAttribute("base", st.getBaseType()); simpleTypeElem.appendChild(restrictionElem); if (st.getPattern() != null) { Element patternElem = doc.createElement("xs:pattern"); patternElem.setAttribute("value", st.getPattern()); restrictionElem.appendChild(patternElem); } } // Write to file with formatting TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("output.xsd")); transformer.transform(source, result);
4. Validate the Generated XSD
Once generated, verify:
- The XSD is well-formed (use an XML validator like Xerces)
- It matches your manual sample structure
- Test it against your XML files to ensure validation works as expected
This approach is scalable—you can extend the model to handle additional restrictions (like enumerations, min/max length) or optional elements as needed from your Excel mapping.
内容的提问来源于stack exchange,提问作者abhi17

