我有一个看起来像这样的输入对象:
myObj = {
"Ob1": {
"myObjName": "A1",
"myObjType": "string",
"myObjOcc": "minOccurs="1""
"Ob2": {
"myObjName": "B1",
"myObjType": "string",
"myObjOcc": "minOccurs="1""
"Ob3": {
"myObjName": "C1",
"myObjType": "string",
"myObjOcc": "minOccurs="1""
}
}
}
"Ob4": {
"myObjName": "A2",
"myObjType": "string",
"myObjOcc": "minOccurs="1""
}
}
我必须以xml模式显示对象:
<xs:complexType name="A1" type="string" minOccurs="1">
<xs:complexType name="B1" type="string" minOccurs="1">
<xs:simpleType name="C1" type="string" minOccurs="1"/>
</complexType>
</complexType>
<xs:simpleType name="A2" type="string" minOccurs="1"/>
想法是,如果对象中有子对象,则为complexType,否则为simpleType。
我有执行打印的这段代码,但是如果有人可以帮助我构造带有缩进的代码:
function isNestedObject(obj) {
for (var o in obj) {
if (isComplexType(o, obj)) {
return true;
}
}
}
function isComplexType(key, obj) {
return (typeof obj[key] === "object");
}
function xsdStructure(obj) {
var str = "",
properties = obj.properties;
if (isNestedObject(obj)) {
if (obj instanceof Array) {
for(var o in obj) {
xsdStructure(obj[o]);
}
}
str += "<xs:complexType name=\"" + obj.attrName + "\" type=\"" + obj.type + "\" " + obj.multiplicty + ">\n";
for (var key in obj) {
var arr = obj[key];
if (arr instanceof Array) {
for (var a in arr) {
str += xsdStructure(arr[a]);
}
}
}
str += "</xs:complexType>\n"
} else {
str = "<xs:simpleType name=\"" + obj.attrName + "\" type=\"" + obj.type + "\" " + obj.multiplicty + "/>\n";
}
return str;
}
function printing(myObj) {
var result = "";
for (var key in object) {
result += xsdStructure(object[key]);
}
result = '<xs:schema>\n'
+ result
+ '</xs:schema>';
return result;
}
它看起来像上面的xml模式,但是我不能使用DOMParser,因此必须手动完成。
预先感谢
答案 0 :(得分:0)
我为您准备了fiddle。我无话可说。首先,在所有与初始对象一起使用的函数中,应使用相同的属性名称。例如:str += "<xs:complexType name=\"" + obj.myObjName + "\" type=\"" + obj.myObjType + "\" " + obj.myObjOcc + ">\n";
而不是您的str += "<xs:complexType name=\"" + obj.attrName + "\" type=\"" + obj.type + "\" " + obj.multiplicty + ">\n";
,也永远不会使此条件为真if (obj instanceof Array)
,因为您的obj根本不包含数组。