来自REST的Javascript循环XML

时间:2017-10-25 14:47:12

标签: javascript xml xml-parsing

如何使用javascript循环上标签的不同子标签,并将标记名和值打印到HTML。一个简短的例子

<Product>
   <Books>
      <Genere>
         <Sport>
            <Name>Book A</Name>
             <Name>Book B</Name>
             <Name>Book C</Name>
          </Sport>
       <Genere>
         <History> 
           <Name>Book A</Name>
           <Name>Book B</Name>
           <Name>Book C</Name>
         </History>
      </Genere>
    </Books>
  <Product>

假设我想以下列方式打印6个书名:

姓名:A书 姓名:书B. 姓名:书C

姓名:A书 姓名:书B. 姓名:书C

我看了一下W3C示例,但它们并没有真正帮助我们。

1 个答案:

答案 0 :(得分:1)

首先,您需要将XML字符串解析为XMLDOM对象。然后,您可以使用该对象的各种方法和属性来导航节点并获取所需的数据。我在下面添加了一个示例。请注意,数据中缺少结束标记(第一个<Genere>节点)。

&#13;
&#13;
//Function to parse XML string into an xml dom object
var parseXML = function(text){
  var xmlDoc;
  if (window.DOMParser){
      var parser = new DOMParser();
      xmlDoc = parser.parseFromString(text, "text/xml");
  } else {
      // Internet Explorer
      xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async = false;
      xmlDoc.loadXML(text);
  }
  return xmlDoc;
}
//Function to get child nodes by name
var getChildrenByName = function(node, name){
  var childNodes = node.childNodes, matchingNodes = [];
  for(var i=0; i<childNodes.length; ++i){
    if(childNodes[i].nodeType !== Node.TEXT_NODE && childNodes[i].tagName == name){
      matchingNodes.push(childNodes[i]);
    }
  }
  return matchingNodes;
}

//Test data
var data = '<Product><Books><Genere><Sport><Name>Book A</Name><Name>Book B</Name><Name>Book C</Name></Sport></Genere><Genere><History><Name>Book A</Name><Name>Book B</Name><Name>Book C</Name></History></Genere></Books><Product>'

//Execute parse
var doc = parseXML(data);

//Get Product node
var product = doc.firstChild;

//Get Books node
var books = getChildrenByName(product, 'Books')[0];

//Get genres
var genres = getChildrenByName(books, 'Genere');

//Loop through genres
var str = '';
for(var i=0; i<genres.length; ++i){
  var genre = genres[i].firstChild;
  str += '<h2>'+genre.tagName+'</h2>';
  //Get book names
  var bookNames = getChildrenByName(genre, 'Name');
  //Loop book names
  for(var j=0; j<bookNames.length; ++j){
    str += bookNames[j].textContent + '<br>';
  }
}

document.body.innerHTML = str;
&#13;
&#13;
&#13;