2

I am trying to parse a large XML file using JavaScript. Looking online, it seems that the easiest way to start is to use the browser's DOM parser. This works, and I can get elements by ID. I can also get the "class" attribute for those elements, and it returns what I would expect. However, I don't appear to be able to get elements by class.

The following was tried in the latest Chrome:

xmlString = '<?xml version="1.0"?>';
xmlString = xmlString + '<example class="test" id="example">content</example>'

parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlString,"text/xml");

xmlDoc.getElementById("example");    
      // returns the example element (good)

xmlDoc.getElementById("example").getAttribute("class");
      // returns "test" (good)

xmlDoc.getElementsByClassName("test");
      // returns [] (bad)

Any ideas?

Sam Fen
  • 5,074
  • 5
  • 30
  • 56
  • Which browser? maybe your browser doesn't support this function? – gdoron May 08 '12 at 17:55
  • 1
    possible duplicate to http://stackoverflow.com/questions/9396354 – Bergi May 08 '12 at 17:58
  • 1
    This will not work, as you are dealing with an XML document, and HTML-specific properties (like `class`) don't apply. However, you can still get elements by tag name, (i.e. `xmlDoc.getElementsByTagName('example');`) - could you perhaps use this to your advantage? – Jim O'Brien May 08 '12 at 17:59
  • ID and ClassName are data types, and in an XML document they are not valid. – adeneo May 08 '12 at 18:02

3 Answers3

1

This should get all elements of a given class, assuming that the tag name will be consistent.

var elements = xmlDoc.getElementsByTagName('Example');
var classArray = [];
for(var i=0;i<elements.length;i++){
    if(elements[i].className=="test"){
        classArray.push(elements[i])
}}
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
empire1138
  • 11
  • 1
  • That almost works, except .className doesn't exist, at least in Chrome, so you have to use getAttribute('class'). I don't know if it's faster than the jQuery parser, though – Sam Fen May 08 '12 at 18:52
0

You can use JQuery to parse an XML file by using a class selector. http://jquery.com

marteljn
  • 6,446
  • 3
  • 30
  • 43
0

Updating the parser type to HTML as opposed to XML should work.

parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlString,"text/html")
boxbit
  • 1
  • 1
  • 2