Xml 简明教程
XML - DOM
Document Object Model (DOM) 是 XML 的基础。XML 文档具有称为节点的信息单元层次结构;DOM 的作用是描述这些节点及其之间的关系。
The Document Object Model (DOM) is the foundation of XML. XML documents have a hierarchy of informational units called nodes; DOM is a way of describing those nodes and the relationships between them.
DOM 文档是由以层次结构组织的节点或信息片段的集合。此层次结构允许开发人员浏览树,查找特定信息。由于 XML DOM 基于信息层次结构,因此 XML DOM 被称为基于树的。
A DOM document is a collection of nodes or pieces of information organized in a hierarchy. This hierarchy allows a developer to navigate through the tree looking for specific information. Because it is based on a hierarchy of information, the DOM is said to be tree based.
另一方面,XML DOM 还提供了一个 API,允许开发人员在树的任何时间点添加、编辑、移动或者删除节点,以便创建应用程序。
The XML DOM, on the other hand, also provides an API that allows a developer to add, edit, move, or remove nodes in the tree at any point in order to create an application.
Example
以下示例 (sample.htm) 将 XML 文档 (“address.xml”) 解析成 XML DOM 对象,然后用 JavaScript 从该对象中提取一些信息 −
The following example (sample.htm) parses an XML document ("address.xml") into an XML DOM object and then extracts some information from it with JavaScript −
<!DOCTYPE html>
<html>
<body>
<h1>TutorialsPoint DOM example </h1>
<div>
<b>Name:</b> <span id = "name"></span><br>
<b>Company:</b> <span id = "company"></span><br>
<b>Phone:</b> <span id = "phone"></span>
</div>
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/xml/address.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById("name").innerHTML=
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
document.getElementById("company").innerHTML=
xmlDoc.getElementsByTagName("company")[0].childNodes[0].nodeValue;
document.getElementById("phone").innerHTML=
xmlDoc.getElementsByTagName("phone")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
address.xml 的内容如下 −
Contents of address.xml are as follows −
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>
现在让我们将这两个文件 sample.htm 和 address.xml 保存在同一个目录 /xml 中,并通过在任何浏览器中打开 sample.htm 文件来执行该文件。这应该会产生以下输出。
Now let us keep these two files sample.htm and address.xml in the same directory /xml and execute the sample.htm file by opening it in any browser. This should produce the following output.
在这里,您可以了解到如何提取每个子节点以显示其值。
Here, you can see how each of the child nodes is extracted to display their values.