Eugeny89
Eugeny89

Reputation: 3731

How to hardcode a large XML string in Javascript?

I'm having a large XML which I need to deal with inside 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?

Is it possible to "embed" that xml file as resource in flash?

Upvotes: 2

Views: 1193

Answers (2)

user823738
user823738

Reputation: 17521

You can try to write it in hex or json representation.

For example, "this string" will become "\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. 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)

"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; use it directly when assigning.

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382274

The usual solution is simply to let the XML file outside and fetch it using an 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.

Upvotes: 5

Related Questions