如何从Jsonix生成的.js映射文件获取元素数据类型及XSD相关问题
Great question! Jsonix mappings encapsulate all the XSD metadata you need, including data types—here's how to extract that information effectively:
1. Navigate the Mapping Structure
Jsonix generates a structured object with two core sections:
elementInfos: Defines top-level XML elements, each linking to its associated type.typeInfos: Contains detailed schema for complex/simple types, including property data types and constraints.
2. Access Type Details Programmatically
Let's use your XSD example (with DocumentElement and Item) to illustrate. Assume your generated mapping is stored in a variable MySchemaMapping:
// Load your generated Jsonix mapping const MySchemaMapping = require('./path/to/your/generated-mapping.js'); // Find the type info for the "Item" complex type const itemType = MySchemaMapping.typeInfos.find(info => info.name === 'Item'); // Loop through Item's properties to get their data types if (itemType) { itemType.properties.forEach(prop => { console.log(`Property: ${prop.name}`); console.log(`Data Type: ${prop.type}`); // For restricted simple types (like your Text_1 element), check base type and facets if (prop.baseType) { console.log(`Base Type: ${prop.baseType}`); if (prop.facets) { console.log(`Restrictions:`, prop.facets); } } }); }
What to Look For:
- Simple types: The
typefield will directly reference XML Schema types (e.g.,xs:string,xs:int). - Complex types:
typewill point to another entry intypeInfos—you can recursively traverse these to get nested property types. - Unbounded elements: For elements like your
Item(withmaxOccurs="unbounded"), the mapping will setmaxOccurstoNumber.POSITIVE_INFINITYor the string"unbounded".
3. Inspect the Mapping Directly
If you don't need to do this programmatically, you can just open the generated .js file in a text editor. Search for your element/type name, and you'll see the type or baseType fields clearly listed alongside the property definitions.
Your partial XSD shows a Text_1 element with a restricted xs:string type. When Jsonix generates the mapping for this, it will include a facets array in the type info for Text_1 that lists all the restriction rules (e.g., pattern, maxLength) from your full XSD. This lets you verify exactly how the type is constrained.
内容的提问来源于stack exchange,提问作者dityagow

