通过元素节点的XML DOM循环

时间:2020-08-26 20:40:43

标签: javascript xml dom

我正在做W3 XML DOM教程。我不明白为什么迭代会在输出中生成1、3、5、7。我了解其他所有内容(我认为!)有人可以帮忙解释一下吗?谢谢。

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();

function myFunction(xml) {
    var x, y, i, xlen, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    x = xmlDoc.getElementsByTagName("book")[0];
    xlen = x.childNodes.length;
    y = x.firstChild;
    txt = "";
    for (i = 0; i < xlen; i++) {
        if (y.nodeType == 1) {
            txt += i + " " + y.nodeName + "<br>";
        }
        y = y.nextSibling;
    }
    document.getElementById("demo").innerHTML = txt; 
}
</script>

</body>
</html>

输出为:

1 title
3 author
5 year
7 price

安迪,你好,这是xml DOM文件,来自https://www.w3schools.com/xml/dom_nodes.asp

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title lang="en">XQuery Kick Start</title>
    <author>James McGovern</author>
    <author>Per Bothner</author>
    <author>Kurt Cagle</author>
    <author>James Linn</author>
    <author>Vaidyanathan Nagarajan</author>
    <year>2003</year>
    <price>49.99</price>
  </book>
  <book category="web" cover="paperback">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

针对Carlos22的回答的其他评论。对不起卡洛斯,我还是不明白。

(y.nodeType ==1)将始终返回true,因为第一次出现的<book>的子代都是元素类型(nodeType = 1)

第一个循环i = 0,因此txt的值应为0 title

第二个循环i = 1,因此0 title应该与1 author连接,因此字符串txt的值现在为0 title 1 author

第三循环i = 2 txt包含字符串0 title 1 author 2 year,依此类推。

有时候我会变得非常愚蠢,所以请原谅!!

3 个答案:

答案 0 :(得分:1)

由于if (y.nodeType == 1),您的代码仅评估“元素节点”。

以下是所有节点的示例:

const xml = `<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title lang="en">XQuery Kick Start</title>
    <author>James McGovern</author>
    <author>Per Bothner</author>
    <author>Kurt Cagle</author>
    <author>James Linn</author>
    <author>Vaidyanathan Nagarajan</author>
    <year>2003</year>
    <price>49.99</price>
  </book>
  <book category="web" cover="paperback">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>`;

function getXmlFromText(xml) {
  parser = new DOMParser();
  return parser.parseFromString(xml, "text/xml");
}

function getNodeTypeStr(nodeType) {
  if (nodeType == 1) return 'ELEMENT_NODE';
  if (nodeType == 3) return 'TEXT_NODE';
  return 'Read the DOCS: https://www.w3schools.com/xml/dom_nodetype.asp';
}

function myFunction(xmlDoc) {
  var x, y, i, xlen, txt;
  //xmlDoc = xml.responseXML;
  x = xmlDoc.getElementsByTagName("book")[0];
  xlen = x.childNodes.length;
  y = x.firstChild;
  txt = ""; var txt2 = '';
  for (i = 0; i < xlen; i++) {
    if (y.nodeType == 1) {
      txt += i + " " + y.nodeName + "<br>";
    }
    txt2 += i + ' - ' + y.nodeName + ' - ' + getNodeTypeStr(y.nodeType) + ' - ' + y.nodeValue + '<br>';
    y = y.nextSibling;
  }
  document.getElementById("demo").innerHTML = txt;
  document.getElementById("allnodes").innerHTML = txt2;
}

myFunction(getXmlFromText(xml));
div {
 padding: 2px;
 border: 1px solid gray;
 margin-bottom: 4px;
}
Only element nodes:
<div id="demo"></div>
All nodes:
<div id="allnodes"></div>

打包的XML示例:

const xml = `<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title><author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title lang="en">XQuery Kick Start</title>
    <author>James McGovern</author>
    <author>Per Bothner</author>
    <author>Kurt Cagle</author>
    <author>James Linn</author>
    <author>Vaidyanathan Nagarajan</author>
    <year>2003</year>
    <price>49.99</price>
  </book>
  <book category="web" cover="paperback">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>`;

function getXmlFromText(xml) {
  parser = new DOMParser();
  return parser.parseFromString(xml, "text/xml");
}

function getNodeTypeStr(nodeType) {
  if (nodeType == 1) return 'ELEMENT_NODE';
  if (nodeType == 3) return 'TEXT_NODE';
  return 'Read the DOCS: https://www.w3schools.com/xml/dom_nodetype.asp';
}

function myFunction(xmlDoc) {
  var x, y, i, xlen, txt;
  //xmlDoc = xml.responseXML;
  x = xmlDoc.getElementsByTagName("book")[0];
  xlen = x.childNodes.length;
  y = x.firstChild;
  txt = ""; var txt2 = '';
  for (i = 0; i < xlen; i++) {
    if (y.nodeType == 1) {
      txt += i + " " + y.nodeName + "<br>";
    }
    txt2 += i + ' - ' + y.nodeName + ' - ' + getNodeTypeStr(y.nodeType) + ' - ' + y.nodeValue + '<br>';
    y = y.nextSibling;
  }
  document.getElementById("demo").innerHTML = txt;
  document.getElementById("allnodes").innerHTML = txt2;
}

myFunction(getXmlFromText(xml));
div {
 padding: 2px;
 border: 1px solid gray;
 margin-bottom: 4px;
}
Only element nodes:
<div id="demo"></div>
All nodes:
<div id="allnodes"></div>

答案 1 :(得分:0)

这是因为验证y.nodeType == 1正确时将其存储在txt += i + " " + y.nodeName + "<br>";中;这意味着当y.nodeType == 1true i为1时,当i为2 y.nodeType == 1为假时,则在下一循环中,当{{1 }}是3 iy.nodeType == 1,依此类推。

答案 2 :(得分:0)

在安东(Anton)和安迪·迈斯纳(Andy Meissner)的帮助下,我学到了一些非常有用的知识!同样在研究了此资源之后:[[关于XML的空白您需要了解的内容]] [1] [1]

可以通过解析器如何处理XML DOM中的空白来解释代码的行为

在以下XML DOM中:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>

很容易想到元素节点<book>有四个子元素,即四个元素<title>, <author>, <year> and <price>,但实际上它有7个孩子,因为解析器会处理空白(回车+换行符) )之后的每个元素节点作为一个空文本节点。

因此,正如安东(Anton)演示的那样,该元素实际上有7个孩子:

child       Type
0           text node (or white space node)
1           element node <title>
2           text node
3           element node <author>
4           text node
5           element node <year>
6           text node
7           element node <price>

代码仅查找元素节点(nodeType = 1),因此处理仅进行if (y.nodeType == 1);

等等,输出为:

1 title
3 author
5 year
7 price


  [1]: https://oracle.com/technical-resources/articles/wang-whitespace.html
相关问题