我似乎无法正确解析JS中的XML数据

时间:2018-09-09 21:12:50

标签: javascript html xml

我有一个输入字段,其中包含以下文本:

<?xml version="1.0" encoding="utf-8"?>
<players timestamp="1536505850">
  <player id="0518" name="Eagles, Philadelphia" position="Def" team="PHI" />
  <player id="10271" name="Jones, Julio" position="WR" team="ATL" />
  <player id="12154" name="Ajayi, Jay" position="RB" team="PHI" />
</players>

我有这些变量:

var outputField = document.getElementById('output');
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(document.getElementById('output'), "text/xml");

当我这样称呼时:

xmlDoc.getElementsByTagName("player")[0].childNodes[0].nodeValue;

我收到此错误:

  

未捕获的TypeError:无法读取在1:1:41处未定义的属性'childNodes'

我在做什么错了?

1 个答案:

答案 0 :(得分:3)

player 元素没有子节点。您需要缩短产生

错误的行
xmlDoc.getElementsByTagName("player")[0].childNodes[0].nodeValue;

xmlDoc.getElementsByTagName("player")[0].nodeValue;

最好知道您要访问的内容,因为上面的语句的评估结果为null

var outputField = document.getElementById('output');

var parser = new DOMParser();
var xmlDoc = parser.parseFromString(outputField.value, "text/xml");

console.log(xmlDoc.getElementsByTagName("player")[0].nodeValue);
<html>
<body>
<textarea id="output">
<?xml version="1.0" encoding="utf-8"?>
<players timestamp="1536505850">
  <player id="0518" name="Eagles, Philadelphia" position="Def" team="PHI" />
  <player id="10271" name="Jones, Julio" position="WR" team="ATL" />
  <player id="12154" name="Ajayi, Jay" position="RB" team="PHI" />
</players>
</textarea>
</body>
</html>


更新:下面是一个如何从“玩家”元素获取属性的示例:

var outputField = document.getElementById('output');

var parser = new DOMParser();
var xmlDoc = parser.parseFromString(outputField.value, "text/xml");

console.log(xmlDoc.getElementsByTagName("player")[0].getAttribute('name'));
<html>
<body>
<textarea id="output">
<?xml version="1.0" encoding="utf-8"?>
<players timestamp="1536505850">
  <player id="0518" name="Eagles, Philadelphia" position="Def" team="PHI" />
  <player id="10271" name="Jones, Julio" position="WR" team="ATL" />
  <player id="12154" name="Ajayi, Jay" position="RB" team="PHI" />
</players>
</textarea>
</body>
</html>