使用默认名称空间解析javascript中xml的最简单方法

时间:2019-06-02 20:36:15

标签: javascript xml parsing namespaces


我正在寻找使用默认名称空间的javascript中解析和xml的简单方法,例如(将其保存到本地文件中):

<?xml version="1.0" encoding="UTF-8"?>
<gpx creator="geoPHP" version="1.1"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://www.topografix.com/GPX/1/1"
  xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" >

<wpt lat="47.626693155617" lon="18.97711568512">
    <ele>426.5</ele>
    <name>first</name>
</wpt>
<wpt lat="47.704416029155" lon="18.876912631094">
    <ele>439.4</ele>
    <name>second</name>
</wpt>
<trk>
    <name>something</name>
    <trkseg>
        <trkpt lat="47.597746001557" lon="19.04898497276">
            <ele>105.6</ele>
        </trkpt>
        <trkpt lat="47.59776301682" lon="19.048692025244">
            <ele>105.4</ele>
        </trkpt>
    </trkseg>
</trk>
</gpx>

html代码是(上面保存的xml的浏览器):

<html>
<body>
 <input type="file" id="gpxfile" onChange="getcounts();"/>
 <div id="result"></div>

<script>
function getcounts() {
 var file = document.getElementById("gpxfile").files[0];
 if (file) {
     var reader = new FileReader();
     reader.readAsText(file, "UTF-8");
     reader.onload = function (evt) {
         var x = evt.target.result||'';
         var txt = "";
         var parser = new DOMParser();
         var xml = parser.parseFromString(x,"text/xml");

         var path = "/gpx/trk/name";
         var nodes = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);
         var tname = nodes.iterateNext();

         document.getElementById("result").innerHTML = tname.textContent;
     }
     reader.onerror = function (evt) {
         document.getElementById("result").innerHTML = "error reading file";
     }
 }
}
</script>
</body>
</html>

如果我从xml中删除 xmlns =“ http://www.topografix.com/GPX/1/1” 行,则它行得通,但不能正常工作。
我不想编写用户定义的nsResolver(如何获得要在其中使用的名称空间?),然后将名称空间前缀添加到xml标记中。必须有一些更简单的解决方案...

0 个答案:

没有答案