Parse XML files and XML strings in JS

Source: Internet
Author: User

Parse XML files and XML strings in JS

Parse XML files using JS

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

<Script type = 'text/javascript '>

LoadXML = function (xmlFile ){

Var xmlDoc = null;

// Determine the browser type

// Supports Internet Explorer

If (! Window. DOMParser & window. ActiveXObject ){

Var xmlDomVersions = ['msxml. 2. DOMDocument.6.0 ', 'msxml. 2. DOMDocument.3.0', 'Microsoft. XMLDOM '];

For (var I = 0; I <xmlDomVersions. length; I ++ ){

Try {

XmlDoc = new ActiveXObject (xmlDomVersions [I]);

Break;

} Catch (e ){

}

}

}

// Supports Mozilla browsers

Else if (document. implementation & document. implementation. createDocument ){

Try {

/* Document. implementation. createDocument ('','', null); three parameters of the Method

* The first parameter is a string that contains the namespace URI used by the document;

* The second parameter is a string containing the document root element name;

* The third parameter is the document type to be created (also called doctype)

*/

XmlDoc = document. implementation. createDocument ('','', null );

} Catch (e ){

}

}

Else {

Return null;

}

If (xmlDoc! = Null ){

XmlDoc. async = false;

XmlDoc. load (xmlFile );

}

Return xmlDoc;

}

</Script>

Parse XML strings using JS

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

<Script type = 'text/javascript '>

LoadXML = function (xmlString ){

Var xmlDoc = null;

// Determine the browser type

// Supports Internet Explorer

If (! Window. DOMParser & window. ActiveXObject) {// window. DOMParser determines whether the browser is a non-IE browser.

Var xmlDomVersions = ['msxml. 2. DOMDocument.6.0 ', 'msxml. 2. DOMDocument.3.0', 'Microsoft. XMLDOM '];

For (var I = 0; I <xmlDomVersions. length; I ++ ){

Try {

XmlDoc = new ActiveXObject (xmlDomVersions [I]);

XmlDoc. async = false;

XmlDoc. loadXML (xmlString); // The loadXML method loads xml strings.

Break;

} Catch (e ){

}

}

}

// Supports Mozilla browsers

Else if (window. DOMParser & document. implementation & document. implementation. createDocument ){

Try {

/* The DOMParser object parses the XML text and returns an XML Document object.

* To use DOMParser, instantiate it using a constructor without parameters, and then call its parseFromString () method.

* ParseFromString (text, contentType) parameter text: content type of the XML tag parameter contentType text to be parsed

* It may be one of "text/xml", "application/xml", or "application/xhtml + xml. Note: "text/html" is not supported ".

*/

DomParser = new DOMParser ();

XmlDoc = domParser. parseFromString (xmlString, 'text/xml ');

} Catch (e ){

}

}

Else {

Return null;

}

Return xmlDoc;

}

</Script>

Test XML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

<? Xml version = "1.0" encoding = "UTF-8"?>

<DongFang>

<Company>

<CNname> 1 </cNname>

<CIP> 1 </cIP>

</Company>

<Company>

<CNname> 2 </cNname>

<CIP> 2 </cIP>

</Company>

<Company>

<CNname> 3 </cNname>

<CIP> 3 </cIP>

</Company>

<Company>

<CNname> 4 </cNname>

<CIP> 4 </cIP>

</Company>

<Company>

<CNname> 5 </cNname>

<CIP> 5 </cIP>

</Company>

<Company>

<CNname> 6 </cNname>

<CIP> 6 </cIP>

</Company>

</DongFang>

Usage

?

1

2

3

4

5

6

Var xmldoc = loadXML (text. xml)

Var elements = xmlDoc. getElementsByTagName ("Company ");

For (var I = 0; I <elements. length; I ++ ){

Var name = elements [I]. getElementsByTagName ("cNname") [0]. firstChild. nodeValue;

Var ip = elements [I]. getElementsByTagName ("cIP") [0]. firstChild. nodeValue;

}

The above method is suitable for IE. Next we will discuss the XML parsing problem in IE and Firefox browsers.

Parse the xml document and xml string for ie and Firefox respectively. All the code has been commented out. Which of the following functions do you want to see,
Just remove the comment.

As for xml parsing in the ajax environment, the principle is the same, but the xml returned must be parsed In the ajax environment.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

<Script>

// Parse the xml document /////////////////////////////////// //////////////////

Var xmlDoc = null;

 

// Supports Internet Explorer

If (window. ActiveXObject ){

XmlDoc = new ActiveXObject ("Microsoft. XMLDOM ");

}

// Supports Mozilla browsers

Else if (document. implementation & document. implementation. createDocument ){

XmlDoc = document. implementation. createDocument ('','', null );

}

Else {

Alert ("here ");

}

If (xmlDoc! = Null ){

XmlDoc. async = false;

XmlDoc. load ("house. xml ");

}

 

// Ie and Firefox are not only different in the parser, but also in the parsing process. As follows;

// Parse xml document with ie

// Alert (xmlDoc. getElementsByTagName ("address") [0]. childNodes [0]. childNodes [0]. childNodes [0]. nodeValue); // 1.5 million is displayed.

// Alert (xmlDoc. getElementsByTagName ("address") [0]. childNodes [0]. childNodes [1]. childNodes [0]. nodeValue); // a three-bedroom apartment is displayed.

 

// Layer-by-layer traversal and parsing childNodes [1]

// Alert (xmlDoc. childNodes [1]. childNodes [1]. childNodes [0]. childNodes [0]. nodeValue); // the 2 million

// Alert (xmlDoc. childNodes [1]. childNodes [0]. childNodes [0]. childNodes [0]. nodeValue); // The 1.5 million

// Alert (xmlDoc. childNodes [1]. childNodes [0]. childNodes [1]. childNodes [0]. nodeValue); // The first room and three residences are displayed.

 

// You can also use item (I) For traversal.

// Var nodesstrap xmldoc.doc umentElement. childNodes;

// Alert (nodes. item (0). childNodes. item (0). childNodes. item (0). text); // 1.5 million is displayed

// Alert (nodes. item (0). childNodes. item (1). childNodes. item (0). text); // The first room and three residences are displayed.

 

// Firefox parses xml documents

// Firefox and ie use textContent to parse different xml node values.

// And it will add the "\ n" line break before and after some child nodes. (I don't know why. It looks like this when debugging with firebug, so it is best to test the code that has been written. It is wrong to change the environment)

// That is to say, 1st nodes are \ n, and 2nd nodes are the real first node.

// 3rd nodes are \ n, and 4th nodes are the real second node.

// Retrieve and parse childNodes through layers [0]

// Alert (xmlDoc. childNodes [0]. childNodes [1]. childNodes [1]. textContent); // 1.5 million is displayed

// Alert (xmlDoc. childNodes [0]. childNodes [1]. childNodes [3]. textContent); // The first room and three residences are displayed.

 

// Directly retrieve the node name and parse getElementsByTagName ("address ")

// Alert (xmlDoc. getElementsByTagName ("address") [0]. textContent); // The first room, third bedroom, 1.5 million, 2 million, 3 million, is displayed.

// Alert (xmlDoc. getElementsByTagName ("address") [0]. childNodes [1]. textContent); // The room 1.5 million, Room 1, and three residences are displayed.

// Alert (xmlDoc. getElementsByTagName ("address") [0]. childNodes [1]. childNodes [1]. textContent); // The 1.5 million

// Alert (xmlDoc. getElementsByTagName ("address") [0]. childNodes [1]. childNodes [3]. textContent); // The first room and three residences are displayed.

// Alert (xmlDoc. getElementsByTagName ("address") [0]. childNodes [3]. textContent); // the 2 million

 

// Firefox can also be traversed using the item (1) function. Note that node "\ n" is added before and after some hierarchical nodes ".

// The first node is item (1), the second node is item (3), and the third node is item (5)

// Item (1) function traversal Parsing

// Var nodesstrap xmldoc.doc umentElement. childNodes;

// Alert (nodes. item (1). textContent); // pop up room 1.5 million, three-bedroom

// Alert (nodes. item (1). childNodes. item (1). textContent); // The 1.5 million

// Alert (nodes. item (1). childNodes. item (3). textContent); // three-bedroom

 

// Parse the xml string /////////////////////////////////// //////////////////////////////////////

Var str = "<car>" +

"<Brand> <price> 0.5 million </price> <pattern> A6 </pattern> </brand>" +

"<Brand> <price> 0.65 million </price> <pattern> A8 </pattern> </brand>" +

"<Brand> <price> 0.17 million </price> </brand>" +

"</Car> ";

 

// Cross-browser, the parser used by ie and Firefox for parsing xml is different.

Var xmlStrDoc = null;

If (window. DOMParser) {// Mozilla Explorer

Parser = new DOMParser ();

XmlStrDoc = parser. parseFromString (str, "text/xml ");

} Else {// Internet Explorer

XmlStrDoc = new ActiveXObject ("Microsoft. XMLDOM ");

XmlStrDoc. async = "false ";

XmlStrDoc. loadXML (str );

}

 

// Parse xml strings with ie

// Alert (xmlStrDoc. getElementsByTagName ("car") [0]. childNodes [0]. childNodes [0]. childNodes [0]. nodeValue); // 0.5 million is displayed.

// Alert (xmlStrDoc. getElementsByTagName ("car") [0]. childNodes [0]. childNodes [1]. childNodes [0]. nodeValue); // the A6 is displayed.

 

// You can also use item (I) For traversal.

// Var strnodesstrap xmlstrdoc.doc umentElement. childNodes;

// Alert (strNodes. item (0). childNodes. item (0). childNodes. item (0). text); // 0.5 million is displayed

// Alert (strNodes. item (0). childNodes. item (1). childNodes. item (0). text); // A6.

 

// Firefox parses xml strings

// Firefox and ie use textContent to parse different xml node values.

// And it will add the "\ n" line break before and after some child nodes.

// That is to say, 1st nodes are \ n, and 2nd nodes are the real first node.

// 3rd nodes are \ n, and 4th nodes are the real second node.

// Alert (xmlStrDoc. childNodes [0]. childNodes [1]. textContent); // The 0.65 million A8

// Alert (xmlStrDoc. childNodes [0]. childNodes [1]. childNodes [1]. textContent); // A8

// Alert (xmlStrDoc. childNodes [0]. childNodes [1]. childNodes [0]. textContent); // 0.65 million is displayed

 

// Firefox can also be traversed using the item (1) function. Note that node "\ n" is added before and after some hierarchical nodes ".

// The first node is item (1), the second node is item (3), and the third node is item (5)

// Var nodesstrap xmlstrdoc.doc umentElement. childNodes;

// Alert (nodes. item (1). textContent); // 0.65 million A8 is displayed.

// Alert (nodes. item (1). childNodes. item (0). textContent); // The 0.65 million

// Alert (nodes. item (1). childNodes. item (1). textContent); // the A8

 

</Script>

 

 

The layer of each xml node is the most annoying problem. You can only try it again and again,
Determine the node hierarchy, or debug it.
I feel that json is better able to read and understand this aspect. This parsing is too hard!

The document house. xml is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<? Xml version = "1.0" encoding = "UTF-8"?>

<Address>

<City name = "Beijing">

<Price> 1.5 million </price>

<Type> one room, three residences </type>

</City>

<City name = "Shanghai">

<Price> 2 million </price>

</City>

<City name = "Hangzhou">

<Price> 2.3 million </price>

</City>

<City name = "Nanjing"> </city>

</Address>

Related Article

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.