简体   繁体   English

用 html 中的 javascript 解析 xml

[英]Parse xml with javascript in html

hello i want to parse serverlist.xml with javascript to a html website.你好,我想用 javascript 解析 serverlist.xml 到一个 html 网站。 its working for me with country, hostname, name, map, numplayers and maxplayers, but when i want to parse the content of "players" with它适用于国家、主机名、名称、地图、numplayers 和 maxplayers,但是当我想解析“玩家”的内容时

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

then i cant see anything more.然后我再也看不到任何东西了。 i guess its because players tags have some more childnodes, but i dont know how to solve this problem.我猜是因为玩家标签有更多的子节点,但我不知道如何解决这个问题。 Thanks for any help.谢谢你的帮助。

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

<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>

From the discussion in the comments, below is a fully working example with a text-to-xml parser function as well as a concise data-type identifier.根据评论中的讨论,下面是一个完整的示例,其中包含一个文本到 xml 解析器函数以及一个简洁的数据类型标识符。

The simplify function uses the above-mentioned functions to limit code duplication and complications, and converts the XML DOM structure into an object (or list of objects). simplify功能使用上述功能来限制代码的重复和复杂化,并将 XML DOM 结构转换为一个对象(或对象列表)。

Each "node" has 3 aspects that represents an XML-node:每个“节点”有 3 个方面,代表一个 XML 节点:

  • Kind - the "nodeName" (tag-name) Kind - “nodeName”(标签名)
  • Attr - the attributes Attr - 属性
  • Data - the contents Data - 内容

You can change these "aspect names" as you see fit.您可以根据需要更改这些“方面名称”。

To test the code, simply copy & paste into a new HTML file, save & open it with your web browser (no web-server needed for this example).要测试代码,只需复制并粘贴到一个新的 HTML 文件中,保存并使用您的网络浏览器打开它(本示例不需要网络服务器)。

The output of this example below will appear in the in the web-console ;下面这个例子的输出将出现在web-console so, just open your web browser's "developer tools" and view the console log.因此,只需打开 Web 浏览器的“开发人员工具”并查看控制台日志。

See the 3 lines of JavaScript in the last <script> element as instructions on how to use it.请参阅最后一个<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>

If you find the code useful, don't forget to "up-vote", thanks ;)如果您发现代码有用,请不要忘记“投票”,谢谢;)

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

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