您好!欢迎访问家园网-www.jy.wang!

家园网

XMLHttpRequest.responseXML 属性扩展示例

网络 作者:本站 点击:

XMLHttpRequest.responseXML 属性扩展示例

基础XML响应示例

const xhr1 = new XMLHttpRequest();
xhr1.open('GET', '/data/books.xml', true);
xhr1.onload = function() {
  const xmlDoc = xhr1.responseXML;
  const books = xmlDoc.getElementsByTagName('book');
  console.log('示例1 - XML文档解析:');
  console.log('根节点:', xmlDoc.documentElement.nodeName);
  console.log('第一本书:', books[0].textContent);
};
xhr1.send();
// 输出可能:
// 根节点: library
// 第一本书: 1984

RSS订阅解析示例

const xhr2 = new XMLHttpRequest();
xhr2.open('GET', '/rss/news', true);
xhr2.onload = function() {
  const xmlDoc = xhr2.responseXML;
  console.log('\n示例2 - RSS订阅解析:');
  console.log('频道标题:', 
    xmlDoc.querySelector('channel title').textContent);
  
  const items = xmlDoc.querySelectorAll('item');
  items.forEach(item => {
    console.log('-', item.querySelector('title').textContent);
  });
};
xhr2.send();
// 输出可能:
// 频道标题: 每日新闻
// - 经济持续增长
// - 科技新突破

SOAP接口调用示例

const xhr3 = new XMLHttpRequest();
xhr3.open('POST', '/soap-api', true);
xhr3.setRequestHeader('Content-Type', 'text/xml');
xhr3.onload = function() {
  const xmlDoc = xhr3.responseXML;
  console.log('\n示例3 - SOAP响应:');
  const result = xmlDoc
    .getElementsByTagName('soap:Body')[0]
    .firstElementChild
    .getAttribute('status');
  console.log('操作状态:', result);
};
xhr3.send('<soap:Envelope>...</soap:Envelope>');
// 输出可能:
// 操作状态: success

SVG图形处理示例

const xhr4 = new XMLHttpRequest();
xhr4.open('GET', '/images/chart.svg', true);
xhr4.onload = function() {
  const svgDoc = xhr4.responseXML;
  console.log('\n示例4 - SVG解析:');
  const paths = svgDoc.getElementsByTagName('path');
  console.log('路径数量:', paths.length);
  document.getElementById('svg-container')
    .appendChild(svgDoc.documentElement);
};
xhr4.send();
// 输出可能:
// 路径数量: 5

错误处理示例

const xhr5 = new XMLHttpRequest();
xhr5.open('GET', '/invalid-xml', true);
xhr5.onload = function() {
  console.log('\n示例5 - 错误处理:');
  if (!xhr5.responseXML || 
      xhr5.responseXML.getElementsByTagName('parsererror').length > 0) {
    console.error('XML解析失败:', xhr5.responseText);
  }
};
xhr5.send();
// 输出可能:
// XML解析失败: <root><item>未闭合标签...

动态更新示例

const xhr6 = new XMLHttpRequest();
xhr6.open('GET', '/live-data', true);
xhr6.onreadystatechange = function() {
  if(xhr6.readyState === 3 && xhr6.responseXML) {
    const updates = xhr6.responseXML
      .getElementsByTagName('update');
    console.log('\n示例6 - 实时更新:');
    console.log('最新消息:', 
      updates[updates.length-1].textContent);
  }
};
xhr6.send();
// 输出可能(多次):
// 最新消息: 用户登录: admin
// 最新消息: 订单创建: #1001


标签: