0

I am now in need of getting some random values from a list of values in XML. Let me explain it clearly. consider it as my XML.

<data>
    <value>
        <name>a</name>
        <age>1</age>
    </value>
    <value>
        <name>b</name>
        <age>2</age>
    </value>
    <value>
        <name>c</name>
        <age>3</age>
    </value>
    <value>
        <name>d</name>
        <age>4</age>
    </value>
    <value>
        <name>e</name>
        <age>5</age>
    </value>
</data>

i have to parse 3 values dynamically in a random manner. i.e. if a,b,c are displayed once the next time when the page loaded it has to display d,b,e or any other in a random order. How i have to deal with it.

4

1 回答 1

0

这是一个将 XML 字符串转换为文档的函数。然后,您可以在文档上使用 DOM 方法:

var stringToXMLDoc = (function(global) {

  // W3C DOMParser support
  if (global.DOMParser) {
    return function (text) {
      var parser = new global.DOMParser();
      return parser.parseFromString(text,"application/xml");
    }

  // MS ActiveXObject support
  } else {
    return function (text) {
      var xmlDoc;

      // Can't assume support and can't test, so try..catch
      try {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(text);
      } catch (e){}
      return xmlDoc;
    }
  }
}(this));

例子:

var xml = '<books>' + 
            '<book title="foo"/>' +
            '<book title="bar"/>' +
            '<book title="baz"/>' +
          '</books>';
var doc = stringToXMLDoc(xml);
alert(
  doc.getElementsByTagName('book')[2].getAttribute('title')
);

您应该能够对值节点执行类似的操作。

于 2012-09-14T08:46:05.820 回答