Javascript:从XMLDocument

时间:2017-04-11 02:29:29

标签: javascript json xml xml-parsing

假设我在var response中存储了以下XMLHttpRequest()。responseText:

{"success":true,"error":null,"body":"<modules>\n <total>5<\/total>\n <status>\n  <id>0<\/id>\n  <name>Archon<\/name>\n  <portCount>14<\/portCount>\n  <attached>true<\/attached>\n <\/status>\n <status>\n  <id>1<\/id>\n  <name>PC4<\/name>\n  <portCount>0<\/portCount>\n  <attached>false<\/attached>\n <\/status>\n <status>\n  <id>2<\/id>\n  <name>APC<\/name>\n  <portCount>0<\/portCount>\n  <attached>false<\/attached>\n <\/status>\n <status>\n  <id>3<\/id>\n  <name>SL1<\/name>\n  <portCount>0<\/portCount>\n  <attached>false<\/attached>\n <\/status>\n <status>\n  <id>4<\/id>\n  <name>SW5-1<\/name>\n  <portCount>0<\/portCount>\n  <attached>false<\/attached>\n <\/status>\n <status>\n  <id>5<\/id>\n  <name>ALC<\/name>\n  <portCount>0<\/portCount>\n  <attached>false<\/attached>\n <\/status>\n <status>\n  <id>65<\/id>\n  <name>VirtualModule<\/name>\n  <portCount>16<\/portCount>\n  <attached>true<\/attached>\n <\/status>\n<\/modules>\n"}

之后,我做了以下提取身体:

var json = JSON.parse(response);
var xml = json.body;

var xml中的对象是一个字符串,所以我试图将其解析为XMLDocument:

var xmlDoc = new DOMParser().parseFromString(xml, 'text/xml');

这里的麻烦是我不知道如何到达子节点。我尝试了以下方法来获取total的值(应该是5):

console.log(xmlDoc.getElementsByTagName("modules")[0].childNodes[0].nodeValue);

但我得到的只是一个空白字符串。我觉得这应该是非常简单的,但我根本就没有得到它。一旦我想获得各种名称标签的价值,我就更无能了。

如何获取子节点的值?

2 个答案:

答案 0 :(得分:1)

字符串不为空。

console.log(xmlDoc.getElementsByTagName("modules")[0].childNodes[0].nodeValue.charCodeAt(0));

10

这是回车的ASCII码。您可以查看here以了解有关childNodeschildren的更多信息。 xmlDoc.children将为您提供一个HTML集合,您可以遍历并从中提取信息。

注意:我建议编辑问题的标题,以便对将来可能会看到它的人更有帮助。

答案 1 :(得分:0)

根据要求,请尝试以下代码。

var response = {"success":true,"error":null,"body":"<modules>\n <total>5<\/total>\n <status>\n  <id>0<\/id>\n  <name>Archon<\/name>\n  <portCount>14<\/portCount>\n  <attached>true<\/attached>\n <\/status>\n <status>\n  <id>1<\/id>\n  <name>PC4<\/name>\n  <portCount>0<\/portCount>\n  <attached>false<\/attached>\n <\/status>\n <status>\n  <id>2<\/id>\n  <name>APC<\/name>\n  <portCount>0<\/portCount>\n  <attached>false<\/attached>\n <\/status>\n <status>\n  <id>3<\/id>\n  <name>SL1<\/name>\n  <portCount>0<\/portCount>\n  <attached>false<\/attached>\n <\/status>\n <status>\n  <id>4<\/id>\n  <name>SW5-1<\/name>\n  <portCount>0<\/portCount>\n  <attached>false<\/attached>\n <\/status>\n <status>\n  <id>5<\/id>\n  <name>ALC<\/name>\n  <portCount>0<\/portCount>\n  <attached>false<\/attached>\n <\/status>\n <status>\n  <id>65<\/id>\n  <name>VirtualModule<\/name>\n  <portCount>16<\/portCount>\n  <attached>true<\/attached>\n <\/status>\n<\/modules>\n"};

var xml = response.body;

var xmlDoc = new DOMParser().parseFromString(xml, 'text/xml');

var allChildNodes = xmlDoc.documentElement.childNodes;

var total = allChildNodes[1].textContent;

alert(total);