将数组字符串项解析为XML

时间:2013-02-17 12:14:03

标签: jquery arrays string parsexml

我正在尝试从数组项中解析XML字符串并遍历其项目但无法使其正常工作!它让我疯了,因为如果我把那个字符串定义为“字符串”它完美地工作......任何帮助?我错过了什么?!

这是以theContent[1]

访问的数组字符串项的内容
<?xml version="1.0" encoding="utf-8" ?>
<ROOT>

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

  ...

</ROOT>

这是阅读项目的代码:

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

正如我所说的,如果我将XML定义为字符串(如下所示),它可以工作,但是当从该数组项字符串中提取xml时它拒绝工作!?

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

@Alexander

“数组”从txt文件加载,其内容如下:

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

我将整个文本拆分为| char,使用第一个数组项作为文本,然后尝试将第二个数组项解析为XML。 正如我在上面解释的那样,我无法读取子文本但是如果我调用alert(typeOf(theContent[1]));它会返回String所以在解析为XML后它应该像我在代码中构建为字符串一样工作,对吧? / p>

1 个答案:

答案 0 :(得分:0)

好吧,我终于明白了......它有点尴尬,但很好,它有效。

源txt文件像任何代码文件一样有换行符,因此,在尝试将字符串解析为XML之前,我必须遍历它,删除任何“返回”和“行”,现在它工作正常。因此,XML解析之前的代码片段是这样的:

// 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());
});

希望它可以帮助别人。

无论如何,谢谢你的关注亚历山大。