我在chrome浏览器中获取xml标签名称长度时遇到问题。当我尝试使用此getElementsByTagName("auth:accountInfo")
时,它在FF上工作正常,但在chrome上却无法工作。如果我使用getElementsByTagName("accountInfo")
,它可以在chrome上运行,但是不能在FF上运行。有人可以帮助我写出适用于两种浏览器的正确逻辑吗?以下是我的示例代码。
objXHR = XMLHttpRequest()
if(objXHR.status == 200)
{
var accountInfo = objXHR.responseXML.getElementsByTagName("auth:accountInfo");
if (accountInfo.length > 0)
{
// do something
}
最佳答案
getElementsByTagNameNS(authNS, 'accountInfo');
authNS
,即您在XML文档中用名称auth
声明的namespaceURI。请注意,您可以通过XPath查询
//auth:accountInfo
实现相同的功能,但是您需要传递namespaceResolver
函数以返回正确的nameSpaceURI。另请注意,此方法隐含更多代码,并且比其他DOM方法慢。最后,您也可以使用
querySelectorAll('*|accountInfo')
实现此目的,但是在这种情况下,无论其名称空间如何,都将选择所有带有tagName accountInfo
的元素。let start = _ =>{
var doc = new DOMParser().parseFromString(sonnet, 'application/xml');
console.log('getElementsByTagNameNS');
console.log(doc.getElementsByTagNameNS("http://www.authors.com/", 'author')[0].outerHTML);
// Alternatively with XPath
function resolveNS(name) {
if (name === 'auth') {
return 'http://www.authors.com/'
}
}
var query = doc.evaluate("//auth:author", doc, resolveNS, XPathResult.ANY_TYPE, null);
var elements = [];
var el;
while (el = query.iterateNext()) {
elements.push(el);
}
console.log('XPATH');
console.log(elements[0].outerHTML)
// Or, with querySelectorAll
console.log('querySelectorAll');
console.log(doc.querySelectorAll('*|author')[0].outerHTML);
};
var sonnet = `<sonnet type='Shakespearean'>
<auth:author xmlns:auth="http://www.authors.com/">
<last-name>Shakespeare</last-name>
<first-name>William</first-name>
<nationality>British</nationality>
<year-of-birth>1564</year-of-birth>
<year-of-death>1616</year-of-death>
</auth:author>
<!-- Is there an official title for this sonnet? They're sometimes named after the first line. -->
<title>Sonnet 130</title>
<lines>
<line>My mistress' eyes are nothing like the sun,</line>
<line>Coral is far more red than her lips red.</line>
<line>If snow be white, why then her breasts are dun,</line>
<line>If hairs be wires, black wires grow on her head.</line>
<line>I have seen roses damasked, red and white,</line>
<line>But no such roses see I in her cheeks.</line>
<line>And in some perfumes is there more delight</line>
<line>Than in the breath that from my ...</line>
</lines>
</sonnet>`;
start();