xml javascript 解析----例程

 

<html  xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>xxxxxxxxxxxxxx</title>

 

</head>

 

<body onload="updateContent()">

<script type="text/javascript">

function updateContent() {

 

var xmlString;

var doc;

var oParser;

xmlString = "<?xml version='1.0' encoding='UTF-8' ?>" +

"<Response>" +

"<GetCommentRsp>" +

"  <totalRecordCount>7</totalRecordCount>" +

" <CommentList>" +

" <Comment>" +

" <commentID>217273</commentID>" +

" <fromUser>135****4193</fromUser>" +

" <time>2010-04-21 13:36:09</time>" +

" <content>册册</content>" +

" </Comment>" +

" <Comment>" +

" <commentID>217273</commentID>" +

" <fromUser>135****4193</fromUser>" +

" <time>2010-04-17 20:34:24</time>" +

" <content>1234567</content>" +

" </Comment>" +

" <Comment>" +

" <commentID>217273</commentID>" +

" <fromUser>135****4193</fromUser>" +

" <time>2010-04-21 13:24:40</time>" +

" <content>好,不错</content>" +

" </Comment>" +

" </CommentList>" +

"</GetCommentRsp>" +

"</Response>";

 

oParser = new DOMParser();

doc = oParser.parseFromString(xmlString, "text/xml");

document.write("<p>" + doc.documentElement.tagName + "</p>");

document.write("<p>" + doc.documentElement.childNodes.length + "</p>");

document.write("<p>" + doc.documentElement.childNodes[0].tagName + "</p>");

document.write("<p>" + doc.documentElement.childNodes[0].childNodes.length + "</p>");

document.write("<p>" + doc.documentElement.childNodes[0].childNodes[1].tagName + "</p>");

document.write("<p>totalRecordCount = " + doc.getElementsByTagName("totalRecordCount")[0].childNodes[0].nodeValue + "</p>");

document.write("<p>" + doc.getElementsByTagName("CommentList").length + "</p>");

document.write("<p>" + doc.getElementsByTagName("CommentList")[0].childNodes.length + "</p>");

document.write("<p>" + doc.getElementsByTagName("CommentList")[0].childNodes[5].tagName + "</p>");

document.write("<p>Comment = " + doc.getElementsByTagName("content")[0].childNodes[0].nodeValue + "</p>");

document.write("<p>" + doc.documentElement.childNodes[0].childNodes[3].tagName + "</p>");

document.write("<p>1</p>");

 

    }

</script>

 

</body>

</html>

 

运行结果如下:

Response

1

GetCommentRsp

4

totalRecordCount

totalRecordCount = 7

1

7

Comment

Comment = 册册

CommentList

1

你可能感兴趣的:(JavaScript,html,xml,function,encoding,2010)