溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

XML中元素和屬性如何讀取

發(fā)布時(shí)間:2020-10-30 12:26:22 來源:億速云 閱讀:111 作者:小新 欄目:編程語言

小編給大家分享一下XML中元素和屬性如何讀取,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!

  1. 元素 與 屬性

  2. 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è)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(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)容。

xml
AI