在html中使用javascript解析xml

时间:2016-05-09 11:03:03

标签: javascript xml xml-parsing

你好我想用javascript将serverlist.xml解析为html网站。它为国家,主机名,姓名,地图,numplayers和maxplayers工作,但当我想用

解析“玩家”的内容时
table +=  x[i].getElementsByTagName("players")[0].childNodes[0].nodeValue;
然后我再也看不到了。我猜它是因为玩家标签有更多的子节点,但我不知道如何解决这个问题。谢谢你的帮助。

serverlist.xml

<qstat>
  <server>
    <hostname>1.2.3.4:27966</hostname>
    <name>Server 1</name>    
    <gametype>Type 1</gametype>
    <map>q3dm3</map>
    <numplayers>3</numplayers>  
    <maxplayers>18</maxplayers>
    <numspectators>0</numspectators>
    <maxspectators>0</maxspectators>
    <ping>0</ping>
    <retries>0</retries>
    <players>
      <player>
        <name>E.Krenz^GDR</name>
        <score>6</score>
        <ping>0</ping>
        </player><player>
        <name>G.Schroeder^GER</name>
        <score>2</score>
        <ping>0</ping>
      </player>
      <player>
        <name>W.Ulbricht^GDR</name>
        <score>1</score>
        <ping>0</ping>
        </player></players>
  </server>
</qstat>

serverlist.html

<html>
<body>
<table id="demo"></table>

<script>
var x,xmlhttp,xmlDoc
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "../serverlist.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName("server");
table='<tr><th bgcolor="#333333">Players</th><th bgcolor="#333333">Country</th><th bgcolor="#333333">Servername</th><th bgcolor="#333333">IP</th><th bgcolor="#333333">Map</th><th bgcolor="#333333">Players</th><th bgcolor="#333333">Connect</th></tr>';
for (i = 0; i <x.length; i++) {
  table += "<tr><td>";
  table +=  x[i].getElementsByTagName("players")[0].childNodes[0].nodeValue;
  table += "</td><td>";
  table += '<iframe src="../serverlist/country/';
  table +=  x[i].getElementsByTagName("hostname")[0].childNodes[0].nodeValue;
  table += '.php" height="25px" width="27px" frameborder="0" scrolling="yes"></iframe>'
  table += "</td><td>";
  table += x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
  table += "</td><td>";
  table +=  x[i].getElementsByTagName("hostname")[0].childNodes[0].nodeValue;
  table += "</td><td>";
  table +=  x[i].getElementsByTagName("map")[0].childNodes[0].nodeValue;
  table += "</td><td>";
  table +=  x[i].getElementsByTagName("numplayers")[0].childNodes[0].nodeValue;
  table += "/";
  table +=  x[i].getElementsByTagName("maxplayers")[0].childNodes[0].nodeValue;
  table += '</td><td><a href="hlsw://';
  table +=  x[i].getElementsByTagName("hostname")[0].childNodes[0].nodeValue;
  table += '/?Connect=1"><img src="../images/hlsw.jpg" width="13" height="13" border="0" />';
  table += '<img src="../images/pixel.png" width="10" height="10" border="0" /><a href="qtracker://';
  table +=  x[i].getElementsByTagName("hostname")[0].childNodes[0].nodeValue;
  table += '?game=quake3&amp;action=connect"><img src="../images/qtracker.jpg" width="13" height="13" border="0" /></a>'
  table += '<img src="../images/pixel.png" width="10" height="10" border="0" /><a href="../serverlist/bat/';
  table +=  x[i].getElementsByTagName("hostname")[0].childNodes[0].nodeValue;
  table += '.bat"><img src="../images/bat.png" width="13" height="13" border="0" /></a>'
  table += "</td></tr>";
}
document.getElementById("demo").innerHTML = table;
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

根据评论中的讨论,下面是一个完整的示例,其中包含text-to-xml解析器函数以及简洁的数据类型标识符。

simplify函数使用上述函数来限制代码重复和复杂性,并将XML DOM结构转换为对象(或对象列表)。

每个“节点”有3个方面代表XML节点:

  • Kind - “nodeName”(标记名称)
  • Attr - 属性
  • Data - 内容

您可以根据需要更改这些“方面名称”。

要测试代码,只需复制&amp;粘贴到新的HTML文件中,另存为&amp;使用您的Web浏览器打开它(此示例不需要Web服务器)。

以下示例的输出将显示在web-console中;所以,只需打开Web浏览器的“开发人员工具”并查看控制台日志。

请参阅上一个<script>元素中的3行JavaScript作为如何使用它的说明。

<html>
    <head></head>
    <body>

        <script>
            function typeOf(data)
            {
                var tpof = (({}).toString.call(data).match(/\s([a-zA-Z]+)/)[1].toLowerCase());

                tpof = (((tpof == 'element') || (tpof == 'window') || (tpof == 'global')) ? 'object' : tpof);
                tpof = (((tpof == 'htmlcollection') || (tpof == 'namednodemap')) ? 'array' : tpof);

                return tpof;
            }



            function parsed(data)
            {
                var text, list;

                if (typeOf(data) == 'string')
                {
                    data = data.trim();
                    text = data.toLowerCase();
                    list = {null:null, true:true, false:false};

                    if (!isNaN(data))
                    { return (data * 1); }

                    if (list[data])
                    { return list[data]; }

                    if ((data.substr(0,1) == '<') && (data.substr(-1,1) == '>'))
                    {
                        var pars = new DOMParser();
                        var dxml = null;

                        try
                        { dxml = pars.parseFromString(data, "application/xml"); }
                        catch(err)
                        { console.log(err); }

                        if (dxml)
                        { return ([].slice.call(dxml.childNodes)); }
                    }

                }

                return data;
            }



            function simplify(dxml)
            {
                var resl, kind, indx=0;
                var list;

                if (typeOf(dxml) == 'array')
                {
                    resl = [];

                    for (var i in dxml)
                    {
                        if (!dxml.hasOwnProperty(i) || !dxml[i].nodeName)
                        { continue; }

                        kind = dxml[i].nodeName;

                        if ((kind == '#text') || (kind == '#comment'))
                        { continue; }

                        resl[indx] = simplify(dxml[i]);
                        indx++;
                    }

                    return resl;
                }


                resl = {Kind:dxml.nodeName.toLowerCase(), Attr:{}, Data:''};

                if (dxml.attributes && (dxml.attributes.length > 0))
                {
                    list = [].slice.call(dxml.attributes);

                    for (var i in list)
                    {
                        if (!list.hasOwnProperty(i) || !list[i].name || !list[i].value)
                        { continue; }

                        resl.Attr[list[i].name] = parsed(list[i].value);
                    }
                }

                if (dxml.childElementCount < 1)
                { resl.Data = (dxml.textContent || ''); }
                else
                { resl.Data = simplify([].slice.call(dxml.childNodes)); }

                return resl;
            }
        </script>


        <script id="xdom" type="text/xmldata">
            <qstat>
            <server>
                <hostname>1.2.3.4:27966</hostname>
                <name>Server 1</name>    
                <gametype>Type 1</gametype>
                <map>q3dm3</map>
                <numplayers>3</numplayers>  
                <maxplayers>18</maxplayers>
                <numspectators>0</numspectators>
                <maxspectators>0</maxspectators>
                <ping>0</ping>
                <retries>0</retries>
                <players>
                <player>
                    <name>E.Krenz^GDR</name>
                    <score>6</score>
                    <ping>0</ping>
                    </player><player>
                    <name>G.Schroeder^GER</name>
                    <score>2</score>
                    <ping>0</ping>
                </player>
                <player>
                    <name>W.Ulbricht^GDR</name>
                    <score>1</score>
                    <ping>0</ping>
                    </player></players>
            </server>
            </qstat>
        </script>


        <script>
            var text = document.getElementById('xdom').innerHTML;
            var xdom = parsed(text);
            var tree = simplify(xdom);

            console.log(tree);
        </script>

    </body>
</html>

如果您发现代码有用,请不要忘记“向上投票”,谢谢;)