0

I'm trying to parseXML a string from an array item and iterate through its items but can't make it work! it's driving me nuts because if I define that string as "string" it works perfectly... any help? What am I missing?!

This is the content of the array string item accessed as theContent[1]:

<?xml version="1.0" encoding="utf-8" ?>
<ROOT>

  <ITEM>
    <NAME>123</NAME>
  </ITEM>

  ...

</ROOT>

This is the piece of code to read the items:

var xmlDOM = $.parseXML(theContent[1]);
var items = $(xmlDOM).find('ROOT ITEM');
$.each(items, function (key, val) {
  alert($(val).find('NAME').text());
});

As I said if I define the XML as string (like below) it works but it refuses to work when pulling the xml from that array item string!?

var theContent = '<?xml version="1.0" encoding="utf-8" ?><ROOT><ITEM><NAME>123</NAME>/ITEM> ... </ROOT>';

@Alexander

The "array" is loaded from a txt file and its something like this:

Some text...|<?xml version="1.0" encoding="utf-8" ?><ROOT><ITEM><NAME>123</NAME>/ITEM> ... </ROOT>

I'm splitting the whole text by the | char, using the 1st array item as a text and then trying to parse the 2nd array item as XML. As I explained above I can't read a child text but if I call an alert(typeOf(theContent[1])); it returns String so after parsed as XML it should work just like when I build as string in code, right?

El Eme
  • 51
  • 3
  • 12

1 Answers1

0

Well I finally figure it out... it's kind of awkward but well, it works.

The source txt file has line breaks like any code file so, before trying to parse the string as XML I had to iterate through it removing any "return" and "line" and now it works fine. So, the piece of code before XML parse is something like this:

// 1st - split the string from the array by '\n'.
var theXML = theContent[1].split("\n");

// 2nd - replace any '\r' with nothing and store it in a new var (xmlString) 
//       that will later be parsed as XML.
var xmlString = "";
$.each(theXML, function (n, elem) {
  elem = elem.replace('\r', '');
  xmlString += elem;
});

// 3rd - now the new string (xmlString) as no '\r' and will be well parsed as XML.
//       the initial var (theXml) is replaced with the resulting parsed XML 
//       and items are accessible.
theXML = $.parseXML(xmlString);
var items = $(theXML).find('ROOT ITEM');
$.each(items, function (key, val) {
  alert($(val).find('NAME').text());
});

Hope it can help others.

Anyway thanks for your attention Alexander.

El Eme
  • 51
  • 3
  • 12