Dom parsing XML (1)

Source: Internet
Author: User
Tags xml parser
XML DOM

Xml dom defines the standard methods for accessing and processing XML documents.

Xml dom is the abbreviation of XML Document Object Model, that is, the XML Document Object Model.

1. Introduction to Dom

What is Dom?

Dom is a W3C recommendation standard.

Dom defines standards for accessing documents such as XML and XHTML.

"W3C Document Object Model (DOM) is an exampleProgramAnd scripts are capable of dynamically accessing and updating the content, structure, style platform, and language-neutral interfaces of documents ."

W3C Dom is divided into three different parts/levels (parts/levels ):

Core dom

Standard Model for any structured document

XML DOM

Standard Model for XML documents

HTML dom

Standard Model for HTML documents

Dom defines the objects and attributes of all document elements and the methods (interfaces) for accessing them ).

What is HTML Dom?

HTML Dom defines the objects and attributes of all HTML elements and the methods (interfaces) for accessing them ).

What is xml dom?

Xml dom is:

Standard Object Model for XML

Standard programming interface for XML

Neutral in platform and language

W3C standards

The xml dom defines the objects and attributes of all XML elements and the methods (interfaces) for accessing them ).

In other words:

Xml dom is a standard used to obtain, modify, add, or delete XML elements.

Ii. xml dom Node

Each component in the document is a node.

Node

According to the Dom, each component in the XML document is a node.

Dom is as follows:

The entire document is a document Node

Each XML tag is an element node.

Text contained in XML elements

Dom instance

See the following XML file (books. XML ):

==============================================

<? XML version = "1.0" encoding = "ISO-8859-1"?>

<Bookstore>

<Book category = "Cooking">

<Title lang = "en"> everyday Italian </title>

<Author> Giada De laurentiis </author>

<Year> 2005 </year>

30.00 </price>

</Book>

<Book category = "children">

<Title lang = "en"> Harry Potter </title>

<Author> j k. Rowling </author>

<Year> 2005 </year>

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> vaidyan#nagarajan </author>

<Year> 2003 </year>

49.99 </price>

</Book>

<Book category = "Web">

<Title lang = "en"> learning XML </title>

<Author> Erik T. Ray </author>

<Year> 2003 </year>

39.95 </price>

</Book>

</Bookstore>

==============================================

In the preceding XML, the root node is <bookstore>. All other nodes in this document are included in <bookstore>.

The root node <bookstore> has four <book> nodes.

The first <book> node has four nodes: <title>, <author>, <year>, and each node contains a text node, "Everyday Italian ", "Giada De laurentiis", "2005" and "30.00 ".

Text is always stored in text nodes.

A common error in Dom processing is that an element node contains text.

However, the text of the element node is stored in the text node.

In this example: <year> 2005 </year>, an element node <year> has a text node with a value of "2005.

"2005" is not the value of the <year> element!

Iii. xml dom node tree

Xml dom treats xml dom documents as a node-tree ).

All nodes in the tree are related to each other.

Xml dom node tree

Xml dom treats XML documents as a tree structure. This tree structure is called a node tree.

You can access all nodes through this tree. They can be modified or deleted, or new elements can be created.

This node tree shows the set of nodes and their relationships. This tree starts from the root node and then grows branches to the text node at the lowest level of the tree.

Parent and peer nodes

Nodes in the node tree have hierarchical relationships with each other.

Parent and peer nodes are used to describe the relationship. A parent node has a child node. A child node at the same level is called a sibling node (brother or sister ).

In the node tree, the top node becomes the root node.

Each node except the root node has a parent node.

Nodes can have any number of subnodes

Leaves are nodes without subnodes

A peer node is a node with the same parent node.

Because XML data is constructed in the form of a tree, you can traverse it without knowing the exact structure of the tree and the Data Types contained in the tree.

4. parse XML DOM

Most browsers have built-in XML Parser for reading and operating XML.

The parser converts XML into JavaScript accessible objects.

Parse XML

All modern browsers have built-in XML Parser for reading and operating XML.

The parser reads XML into the memory and converts it to an xml dom object accessed by JavaScript.

Microsoft's XML parser is different from the parser in other browsers. Microsoft's parser supports loading XML files and XML strings (text), while other browsers use separate Resolvers. However, all Resolvers contain functions that traverse the XML tree, access, insert, and delete nodes.

V. xml operations in Javascript

We know that in XML documents, element nodes, attribute nodes, and text nodes are mainly used.

The following describes in detail how JavaScript operates on them.

Element Node:

Search: Introduced in the previous article. It mainly finds and locates through getelementsbytagname.

Example:

// Output all titles

VaR T = xmldoc. getelementsbytagname ("title ");

For (I = 0; I <t. length; I ++)

{

Document. Write (T. Childnodes [0]. nodevalue );

Document. Write ("<br/> ");

}

Add: Create an element using createelement and appendchild to add a subnode.

Example:

VaR newnode = xmldoc. createelement ("new element name"); // create an element node

VaR nodebook = xmldoc. getelementsbytagname ("book") [0]; // locate the node book

Nodebook. appendchild (newnode); // append newnode as a subnode to the subnode of the parent node book. That is to say, to append a node, you must first find the parent node.

You can also add nodes by cloning them.

The clonenode () method has a parameter (true or false ). This parameter indicates whether the copied node includes all attributes and subnodes of the original node.

Example:

Oldnode = xmldoc. getelementsbytagname ('book') [0];

Newnode = oldnode. clonenode (true); // clone and copy the original node and all attributes and subnodes

Xmldoc.doc umentelement. appendchild (newnode );

Delete: The parent node calls removechild.

For example:

VaR nodebook = xmldoc. getelementsbytagname ("book") [0]; // locate the node book

Xmldoc.doc umentelement. removechild (nodebook); // Delete the first book node under the root node

Note: When a node is deleted, its subnodes are also deleted.

Modify: Directly modifying elements is not allowed. You can use replaceChild to modify the modification.

Syntax: parentnode. replaceChild (newnode, oldnode)

In addition, the element does not have nodevalue. To modify the text in the element, such as modifying the hello in <title> Hello </title>, refer to the following operationsCompositionThis node.

Text node:

Search: You cannot use getelementsbytagname to search for a text node. Instead, you can use it to find the element node, then, use childnodes [0] Or firstchild to locate the text node (because it exists in the form of the first subnode of the element node), and then use nodevalue to obtain the text content.

Example:

VaR nodetitle = xmldoc. getelementsbytagname ("title") [0];

VaR titletextnode = nodetitle. childnodes [0]; // you can also use firstchild

VaR thetxt = titletextnode. nodevalue;

Add: It is similar to the method for adding elements, but the text is created through createtextnode (Note: You can also add the content in XHTML using innerhtml ).

Example:

VaR edition = xmldoc. createelement ("edition ");

VaR newtext = xmldoc. createtextnode ("this is first ");

Edition. appendchild (newtext); // when operating XHTML, the above two rows can be directly replaced by edition. innerhtml = 'this is first;

VaR nodebook = xmldoc. getelementsbytagname ("book") [0];

Nodebook. appendchild (Edition );

Delete: The parent node calls removechild. Of course, nodevalue can also be cleared. For example, textnode. nodevalue = ''.

Modify: Textnode. nodevalue = 'modify to the text content you want '.

In addition, you can use replacedata () to replace data in a text node.

The replacedata () method has three parameters:

Offset-where to start replacement characters. The offset value starts with 0.

Length-the number of characters to replace .,

String-the string to be inserted.

Example:

Xmldoc. getelementsbytagname ("title") [0]. childnodes [0]. replacedata (0, 8, "hello ");

// Note: in fact, you can use substr or substring to process the string in advance and assign it to nodevalue.

Attribute node:

Search: Unlike element nodes, attribute nodes have text values. The method to get the attribute value is to get its text value. You can use the getattribute () method or the nodevalue attribute of the attribute node to complete this task.

Example:

Xmldoc. getelementsbytagname ("title") [0]. getattribute ("Lang"); // return "en"

Or

Xmldoc. getelementsbytagname ("title") [0]. getattributenode ("Lang"). nodevalue; // return "en"

Add: Use setattribute or setattributenode.

Example:

Xmldoc. getelementsbytagname ('book') [0]. setattribute ("edition", "this is first ");

Or

VaR newatt = xmldoc. createattribute ("edition ");

Newatt. nodevalue = "this is first ";

Xmldoc. getelementsbytagname ("title") [0]. setattributenode (newatt );

Delete: Removeattribute (name) or removeattributenode (node) are available)

Example:

// Method 1: removeattribute

// Delete the "category" attribute in the first <book> element:

Xmldoc. getelementsbytagname ("book") [0]. removeattribute ("category ");

// Method 2: removeattributenode

// Delete all attributes of all <book> Elements

X = xmldoc. getelementsbytagname ("book ");

For (I = 0; I <X. length; I ++)

{

While (x. Attributes. length> 0)

{

Attnode = x. Attributes [0];

Old_att = x. Removeattributenode (attnode );

}

}

Modify: Use the setattribute () method or the nodevalue attribute of the attribute node.

Example:

// Setattribute

Xmldoc. getelementsbytagname ('book') [0]. setattribute ("category", "child ");

// Set nodevalue

VaR x = xmldoc. getelementsbytagname ("book") [0]

Var y = x. getattributenode ("category ");

Y. nodevalue = "child ";

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.