在 html 中使用 javascript 解析 xml

Parse xml with javascript in html

本文关键字:javascript 解析 xml html      更新时间:2023-09-26

你好,我想用javascript解析ServerList.xml到一个html网站。 它对我使用国家、主机名、名称、地图、数字玩家和最大播放器对我有用,但是当我想解析"玩家"的内容时

table +=  x[i].getElementsByTagName("players")[0].childNodes[0].nodeValue;

然后我什么也看不到了。 我想这是因为玩家标签有更多的子节点,但我不知道如何解决这个问题。感谢您的任何帮助。

服务器列表.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>

服务器列表.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>

从注释中的讨论来看,下面是一个完整的工作示例,其中包含文本到 xml 解析器函数以及简洁的数据类型标识符。

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

每个"节点"都有 3 个方面来表示一个 XML 节点:

  • Kind - "节点名称"(标记名称(
  • Attr - 属性
  • Data - 内容

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

要测试代码,只需复制并粘贴到一个新的HTML文件中,使用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>

如果您发现代码有用,请不要忘记"赞成",谢谢;)