-1

i have a xml file which has field tags like

    <!-- 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"/>

how to parse the xml field tags using javascript I have tried the following code but of no use

<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>
  • Duplicate of https://stackoverflow.com/questions/17604071/parse-xml-using-javascript – Hiteshdua1 Jun 20 '18 at 09:32
  • but the answer does not tell about field tags parsing of xml – Pradeepta Choudhury Jun 20 '18 at 09:34
  • Please see the answer for reference for sample field tags – Hiteshdua1 Jun 20 '18 at 09:47
  • The name of the XML element shouldn't matter - how use parse XML is the same in both cases. You parse the XML, then use `getElementsByTagName` and friends to retrieve the nodes you're interested in. What doesn't work in your example? What are you trying to extract? What do you want the result to be? – MatsLindh Jun 20 '18 at 09:50
  • Possible duplicate of [Parse XML using JavaScript](https://stackoverflow.com/questions/17604071/parse-xml-using-javascript) – Anders R. Bystrup Jun 20 '18 at 11:10

1 Answers1

0

I guess thid would work :

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"));
Hiteshdua1
  • 2,126
  • 18
  • 29