nkn*_*nkn 8 javascript xml arrays json
我正在尝试将 JSON 转换为 XML 但没有得到确切的输出。在我的 JSON 有数组对象它没有将其转换为 XML 数组。主要是数组对象没有按预期转换为 XML
var InputJSON = "{"body":{"entry": [{ "fullURL" : "abcd","Resource": "1234"},{ "fullURL" : "efgh","Resource": "5678"}]}}";
var output = eval("OBJtoXML("+InputJSON+");")
function OBJtoXML(obj) {
var xml = '';
for (var prop in obj) {
xml += "<" + prop + ">";
if(obj[prop] instanceof Array) {
for (var array in obj[prop]) {
xml += OBJtoXML(new Object(obj[prop][array]));
}
} else if (typeof obj[prop] == "object") {
xml += OBJtoXML(new Object(obj[prop]));
} else {
xml += obj[prop];
}
xml += "</" + prop + ">";
}
var xml = xml.replace(/<\/?[0-9]{1,}>/g,'');
return xml
}
Run Code Online (Sandbox Code Playgroud)
实际输出:
<body>
<entry>
<fullURL>abcd</fullURL>
<Resource>1234</Resource>
<fullURL>efgh</fullURL>
<Resource>5678</Resource>
</entry>
</body>
Run Code Online (Sandbox Code Playgroud)
预期输出:
<body>
<entry>
<fullURL>abcd</fullURL>
<Resource>1234</Resource>
</entry>
<entry>
<fullURL>efgh</fullURL>
<Resource>5678</Resource>
</entry>
</body>
Run Code Online (Sandbox Code Playgroud)
如果我遗漏了代码中的任何内容以获得预期结果,请指导我
Usm*_*ali 12
将您的OBJtoXML功能替换为
function OBJtoXML(obj) {
var xml = '';
for (var prop in obj) {
xml += obj[prop] instanceof Array ? '' : "<" + prop + ">";
if (obj[prop] instanceof Array) {
for (var array in obj[prop]) {
xml += "<" + prop + ">";
xml += OBJtoXML(new Object(obj[prop][array]));
xml += "</" + prop + ">";
}
} else if (typeof obj[prop] == "object") {
xml += OBJtoXML(new Object(obj[prop]));
} else {
xml += obj[prop];
}
xml += obj[prop] instanceof Array ? '' : "</" + prop + ">";
}
var xml = xml.replace(/<\/?[0-9]{1,}>/g, '');
return xml
}
Run Code Online (Sandbox Code Playgroud)
使用xml-js库
import { json2xml } from "xml-js";
const input = {
contact: {
name: `John & cia "example"`
}
};
const xml = json2xml(input, {
compact: true
});
// <contact><name>John & cia \"example\"</name></contact>
Run Code Online (Sandbox Code Playgroud)
https://codesandbox.io/s/xml-json-forked-zgit4?file=/src/index.js:97-103
:)
| 归档时间: |
|
| 查看次数: |
23028 次 |
| 最近记录: |