简体   繁体   English

如何用Javascript硬编码较大的XML字符串?

[英]How to hardcode a large XML string in Javascript?

I'm having a large XML which I need to deal with inside JS. 我有一个很大的XML,需要在JS内部处理。 Is there a better solution then to copy/paste (from xml file to js file) and quote each of nearly 1000 lines of xml file? 有没有更好的解决方案,然后复制/粘贴(从xml文件到js文件)并引用近1000行xml文件中的每行?

Is it possible to "embed" that xml file as resource in flash? 是否可以将该XML文件“嵌入”为Flash中的资源?

The usual solution is simply to let the XML file outside and fetch it using an XMLHttpRequest : 通常的解决方案是将XML文件放到外面,然后使用XMLHttpRequest来获取它:

function fetchXMLFile(url, callback) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                var xml = httpRequest.responseXML;
                if (callback) callback(xml);
            }
        }
    };
    httpRequest.open('GET', url);
    httpRequest.send(); 
}

fetchFile('myFile.xml', function(xml){
   // use the xml
});

If you really want to embed the data in the code, you'll have to play with regexes in your favorite editor or to build a small tool to do the embedding but it's rarely considered a best practice to merge big data with source code. 如果您确实想将数据嵌入代码中,则必须在自己喜欢的编辑器中使用正则表达式,或者构建一个小的工具来进行嵌入,但是很少有人认为将大数据与源代码合并是一种最佳实践。 Both parts usually have a different life cycle. 这两个部分通常具有不同的生命周期。

You can try to write it in hex or json representation. 您可以尝试以十六进制或json表示形式编写它。

For example, "this string" will become "\\x74\\x68\\x69\\x73\\x20\\x73\\x74\\x72\\x69\\x6e\\x67". 例如,“此字符串”将变为“ \\ x74 \\ x68 \\ x69 \\ x73 \\ x20 \\ x73 \\ x74 \\ x72 \\ x69 \\ x6e \\ x67”。 There are tons of online tools that do this for you. 有大量的在线工具可以帮助您。 For example this one , will do the work but wont include the "\\x", so javascript'll interpret it as normal string. 例如, 这个将完成工作,但不会包含“ \\ x”,因此javascript将其解释为普通字符串。 To append the \\x and have the right hex format execute this function on the fly in any javascript console:(of course replace the quoted text with generated hex digits) 要附加\\ x并具有正确的十六进制格式,请在任何javascript控制台中即时执行此功能:(当然,将引号引起的文本替换为生成的十六进制数字)

"7468697320737472696e67".replace(/([A-F\d]{2})/gi, "\\x$1"); // \x74...\x67

then just copy this string into your source and it should work. 然后只需将此字符串复制到您的源中,它就可以工作。 If you want to parsed xml, take a look at this - another online tool to convert your xml to json, valid javascript object; 如果你想解析XML,看看这个 -其他在线工具将XML转换成JSON,有效的JavaScript对象; use it directly when assigning. 分配时直接使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM