0

I'm trying to display some XML data in a jsp file.

I'm using EL to get the data below:

<xml id="xmlData">
    <c:out value="${xmlform.myXmlData}" escapeXml="false"/>
</xml>

How can I get reference to this xml document using javascript?

var xmlDoc  = document.getElementById("xmlData"); //reference to the xml element 
var xmlData = xmlDoc.[how to reference xmlDoc to get data?]
var fields  = xmlData.documentElement.selectNodes("field");
for (var i=-; i<fields.length;etc...
1
  • Where does this xml appear? In the HTML of a web page? As a result from an ajax request? Commented Aug 7, 2014 at 19:09

3 Answers 3

1

So the JSP-Server write the XML-tree directly in the HTML-code. I hope this could be helpful for you.

var parser = new DOMParser();
var xmlDoc = parser.parseFromString(document.getElementById("xmlData").innerHTML ,"text/xml");
var fields = xmlDoc.documentElement.getElementsByTagName("field");
for(var i = 0; i < fields.length; i++)
{
    console.log(fields[i].firstChild.data); // fields[i].attributes, fields[i]childNodes, ...
}

or shorter:

var xmlData = document.getElementById("xmlData");
var fields = xmlData.getElementsByTagName("field");
for(var i = 0; i < fields.length; i++)
{
    console.log(fields[i].firstChild.data);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Here is how you can parse XML in javascript.

var xmlDoc;

function parsexml(txt)
{
    if (window.DOMParser)
      {
      parser=new DOMParser();
      xmlDoc=parser.parseFromString(txt,"text/xml");  //txt is your xml data
      }
    else // Internet Explorer
      {
      xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async=false;
      xmlDoc.loadXML(txt); 
      }
}
function getElementFromXML(tagname)
{
return xmlDoc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}

Comments

1

You have to load your xml file in and then find and manipulate the Nodes as needed.

function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  }
else // code for IE5 and IE6
  {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}

All modern browsers have a built-in XML parser.

An XML parser converts an XML document into an XML DOM object - which can then be manipulated with JavaScript.

W3Schools example

2 Comments

Thanks for the tip user, will look into this
Please don't use W3Schools. Use MDN instead. Examples can be hosted on jsfiddle.net

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.