将xml文件数据保存在javascript变量中

时间:2013-04-06 10:27:55

标签: javascript xml xml-parsing youtube

我搜索了我的问题并发现了很多我已经使用过的有用的东西。

这是计划: 我想将xml文件中的数据加载到javascript变量中。读取xml数据的DOMParser函数将其推送到数组中,因此我可以稍后从数组中获取随机元素。

要了解我想要做什么:我想加载随机的YouTube视频。视频的链接/结尾存储在xml文件中,如“d_HvwKtsy_Q”。视频结束后,应立即启动下一个视频。我已经知道如何在YT api中执行此操作..我只需要将xml文件加载到变量中,因此我可以在extern xml文件中对其进行编辑。

这是我到目前为止所得到的:

// This is my "xml file", but i want to have it in a extern file, so the variable      
stores the extern xml file data like "externXMLfile.xml"

var xml_string ='<answers><answer id="0">o6f9wJ1DWhY</answer><answer    id="1">72Y7M3_NlfI</answer></answers>'


function get_answers_from_xml_string(xml_string) {
// Parse the XML string into a XMLDocument
var doc = window.DOMParser
            ? new DOMParser().parseFromString(xml_string, 'text/xml')    // Standard
            : new ActiveXObject('Microsoft.XMLDOM').loadXML(xml_string); // IE

// Find the answer nodes
var answers_nodes = doc.getElementsByTagName('answer');
var answers = [];

// Loop through them and save their text content into an array
for (var i = 0; i < answers_nodes.length; i++) {
    answers.push(answers_nodes[i].firstChild.data)
}

return answers;
}


//Save the xml elements in an array called answers
var answers = get_answers_from_xml_string(xml_string);

//This is the youtube api stuff, which works fine
    // create youtube player
    var player;
    function onYouTubePlayerAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'd_HvwKtsy_Q',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange,

          },
          playerVars: {

                    'controls': 0,
                    'showinfo': 0,
                    'iv_load_policy': 3,
                },
        });
    }


//this function loads a new random video id after the video stops from the array, which stores the xml elements

function getMessage() {
return answers[Math.floor(Math.random() * answers.length)];
}

    function swapVideo() {     
player.stopVideo();
player.loadVideoById(getMessage());


}
// autoplay video
    function onPlayerReady(event) {
        event.target.playVideo();
    }

// when video ends
    function onPlayerStateChange(event) {        
        if(event.data === 0) {          
           swapVideo();
        }
    }

我希望你能理解我的问题我认为除了将xml_string变量与extern xml文件连接外,几乎所有东西都是

感谢您的帮助!!

2 个答案:

答案 0 :(得分:0)

这样的事可以帮到你

 System.IO.StreamReader file = new System.IO.StreamReader(@"c:\YourXML.xml");
    string test = file.ReadToEnd();

您也可以参考 How can I save the this XML to a C# string variable?

答案 1 :(得分:0)

终于想通了!感谢Darshan的正确链接。

https://stackoverflow.com/a/8680038/1870659

var jqxhr = $.ajax({
type: 'POST',       
url: "freeakshow.xml",
dataType: 'xml',
global: false,
async:false,
success: function(data) {
    return data;
}
}).responseText;


xml_string = jqxhr;