如何使用javascript解析xml文件字段标签

时间:2018-06-20 09:31:23

标签: javascript xml solr nutch

我有一个xml文件,其中包含诸如         

    <!-- fields for index-anchor plugin -->
    <field name="anchor" type="string" stored="true" indexed="true"
        multiValued="true"/>

    <!-- fields for index-more plugin -->
    <field name="type" type="string" stored="true" indexed="true"
        multiValued="true"/>
    <field name="contentLength" type="long" stored="true"
        indexed="false"/>

如何使用javascript解析xml字段标签 我尝试了以下代码,但没有用

<script>
function loadXMLDoc() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      myFunction(this);
    }
  };
  xmlhttp.open("GET", "schema.xml", true);
  xmlhttp.send();
}

function myFunction(xml) {
  var x, i, xmlDoc, txt;
  xmlDoc = xml.responseXML;
  txt = "";
    x = xmlDoc.getElementsByTagName("field");
    for (i = 0; i< x.length; i++) {
    txt += x[i].childNodes[0].nodeValue +"<br>";
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

1 个答案:

答案 0 :(得分:0)

我想这会起作用:

var text = `
    <!-- fields for index-anchor plugin -->
    <field name="anchor" type="string" stored="true" indexed="true"
        multiValued="true"/>

    <!-- fields for index-more plugin -->
    <field name="type" type="string" stored="true" indexed="true"
        multiValued="true"/>
    <field name="contentLength" type="long" stored="true"
        indexed="false"/>
`;

if (window.DOMParser)
{
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(text, "text/xml");
}
else // Internet Explorer 
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(text);
}


console.log(xmlDoc.getElementsByTagName("field")[0].getAttribute("name"));