javascript读取xml

本文介绍了一种使用JavaScript实现的XML文件解析方法,通过自定义类处理XML文档,并获取其中员工的信息,包括姓名、职位及薪资等数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

data.xml
<?xml version="1.0" encoding="gb2312"?>
<employees>
     <employee name="Billgates">
          <job>Programmer</job>
          <salary>32768</salary>
     </employee>
     <employee name="王涛">
          <job>无业游民</job>
          <salary>70000</salary>
     </employee>
     <employee name="Big 中华">
          <job>哈尔滨CEO</job>
          <salary>100000</salary>
     </employee>
</employees>

<script language="javascript">
//类的构造,传入xml文档和需要处理的标签名称
function DataSet(xmlFile, tagLabel) {
  var xmldoc;
  if(window.ActiveXObject){
    xmldoc=new ActiveXObject("Microsoft.XMLDOM");
  }else if(document.implementation&&document.implementation.createDocument){
    xmldoc=document.implementation.createDocument("","doc",null);
  }
  xmldoc.async = false;
  xmldoc.load(xmlFile);
  this.rootObj = xmldoc.getElementsByTagName(tagLabel)
 
  this.getCount = getCount;
  this.getData = getData;
  this.getAttribute = getAttribute;
  this.getNodeAttribute=getNodeAttribute;
}
function getCount(){
  return this.rootObj.length
}
function getData(index, tagName){
  if (index >= this.count) return "index overflow"
  var node = this.rootObj[index]
  var str = node.getElementsByTagName(tagName)[0].firstChild.data
  return str
}
function getAttribute(index, tagName) {
  if (index >= this.count) return "index overflow"
  var node = this.rootObj[index]
  var str = node.getAttribute(tagName)
  return str
}
function getNodeAttribute(index,node,tagName){
  if(index>=this.rootObj[index].childNodes.length)return "index overflow";
  var str=this.rootObj[index].childNodes[node].getAttribute(tagName);
  return str;
}
var set=new DataSet("data.xml","employee");
alert(set.getCount());
alert(set.getAttribute(2,"name"));
alert(set.getData(1,"job"));
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值