JavaScript 解析 XML 错误:Cannot read properties of undefined (reading 'getElementsByTagName')
在这段代码中,出现报错的地方是 parseXML(xmlString).getElementsByTagName('person'),报错信息是 Cannot read properties of undefined (reading 'getElementsByTagName')。这是因为 parseXML 函数返回的是一个 XML 文档对象,而不是一个节点对象。所以无法直接调用 getElementsByTagName 方法。
要解决这个问题,可以将 parseXML 函数的返回值改为返回一个 XML 文档对象(即 xmlDoc),然后在外部使用 xmlDoc 对象来获取节点。修改后的代码如下:
function parseXML(xmlString) {
const serializer = new XMLSerializer();
const xmlDoc = serializer.serializeToString(new DOMParser().parseFromString(xmlString, 'application/xml'));
return xmlDoc.documentElement.nodeName === 'parsererror' ? null : xmlDoc;
}
const xmlString = `<root>
<person>
<name>John</name>
<age>30</age>
</person>
<person>
<name>Jane</name>
<age>28</age>
</person>
</root>`;
const xmlDoc = parseXML(xmlString);
if (xmlDoc) {
const personNodes = xmlDoc.getElementsByTagName('person');
console.log(personNodes.length); // 输出:2
} else {
console.log('解析 XML 失败');
}
这样就能正确获取到 <person> 节点的数量了。
原文地址: https://www.cveoy.top/t/topic/qxVr 著作权归作者所有。请勿转载和采集!