将 JavaScript 程序从 JSON 转换为 XML

converting javascript program from json to xml

本文关键字:转换 XML JSON JavaScript 程序      更新时间:2023-09-26

我正在将一个使用 json 文件的 javascript 程序重写为使用 xml 文件进行设置的程序。我拥有的 xml 文件与 json 文件的结构不同,我打算将一些 json 变量硬编码到程序中。我认为最简单的方法是不重新编码对 json 数据的所有调用,因此我正在尝试创建看起来像 json 数据的对象,并具有自己的函数来在需要时将 xml 数据加载到对象中。

注意 我以前从未搞砸过 json。 如果您认为可能有更好的方法,我很乐意尝试。

我已经想出的简单 json 文件,只需创建一个看起来相同的类。

 {
"logo": "yes",
"title": "Jordan Pond",
"author": "Matthew Petroff",    
"license": 1,    
"preview": "../examples/examplepano-preview.jpg",
}

变成

function config(){
    this.logo='yes';
    this.title='Jordan Pond';
    this.author='Matthew Petroff';
    this.license='1';
    this.preview='./examples/examplepano-preview.jpg';
}
config= new config();
alert(config.title);

这样做,对 json 内容的所有调用都与往常一样工作。我被更复杂的json文件难倒

了,例如
{
"default": {
    "license": 0,
    "logo": "no",
    "author": "Kvtours.com",
    "firstScene": "WilsonRiverFishingHole",
    "title": "Wilson"
},
"scenes": {
    "pond": {
        "title": "Jordan Pond",
        "preview": "../examples/examplepano-preview.jpg",
        "panorama": "../examples/examplepano.jpg"
    }
}
}

我认为应该转换为这样的东西。

function tourConfig(){
this.default= function() {
    license= "0";
    logo= "no";
    author= "Kvtours.com";
    firstScene= "pondCube";
    title= "Wilson";
}
this.scenes= function(){
    this.pondCube= function() {
        this.title= "Jordan Pond (Cube)";
        this.preview="examples/examplepano-preview.jpg";
        this.panorama="../examples/examplepano.jpg";
    }
}
}
tourConfig= new tourConfig();
alert(tourConfig.default.author);

这是行不通的。关于如何让它工作的任何想法?

你对javascript闭包感到困惑。

我认为您想要的如下:

function tourConfig(){
    var that = this;
    this.default= function() {
        that.license= "0";
        that.logo= "no";
        that.author= "Kvtours.com";
        that.firstScene= "pondCube";
        that.title= "Wilson";
    }
    // as well as scenes method
}