您好,登錄后才能下訂單哦!
小編給大家分享一下XML中元素和屬性如何讀取,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
元素 與 屬性
javascript讀取XML文件:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<note>
<to>duncan
</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
XML DOM 操作XML
<html>
<head>
<script type="text/javascript">
function parseXML()
{
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc=document.implementation.createDocument("","",null);
}
catch(e)
{
alert(e.message);
return;
}
}
xmlDoc.async=false;
xmlDoc.load("note.xml");
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
}
</script>
</head>
<body onload="parseXML()">
<h2>W3School.com.cn Internal Note</h2>
<p><b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span>
</p>
</body>
</html>
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue
xmlDoc -由解析器創(chuàng)建的 XML 文檔
getElementsByTagName("to")[0] - 第一個(gè) <to> 元素
childNodes[0] - <to> 元素的第一個(gè)子元素(文本節(jié)點(diǎn))
nodeValue - 節(jié)點(diǎn)的值(文本本身)
疑問:
如果xml文件為:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<note>
<to>asdfsd
<too>duncan1</too>
</to>
<too>duncan2</too>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
讀取第一個(gè)<too>
xmlDoc.getElementsByTagName("to")[0].getElementsByTagName("t00")[0].childNodes[0].nodeValue
讀取第二個(gè)<too>
xmlDoc.getElementsByTagName("too")[0].childNodes[0].nodeValue
看完了這篇文章,相信你對XML中元素和屬性如何讀取有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。