HTML中隐藏标签和显示标签的例子
注意登录前后的变化
HTML的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>天天生鲜</title>
<link rel="stylesheet" href="../css/register.css">
<link rel="stylesheet" href="../css/main.css">
</head>
<body>
<!-- 1.login部分,天天生鲜欢迎您! -->
<div id="login">
<div class="login">
<!-- 1.1 login内容部分 -->
<div class="loginbox">
<!-- 1.11 左侧欢迎栏 -->
<h3>欢迎您来天天生鲜!</h3>
<!-- 1.12右侧我的订单 -->
<div class="loginrg">
<!-- 1.121 已经登录 -->
<div class="inlogin" id="inlogin">
欢迎您:
<a href=""><span id="username"></span></a>
</div>
<div class="unlogin" id="unlogin">
<a href="#" onclick="show()">登录</a>
<span>|</span>
<a href="register.html">注册</a>
</div>
<!-- 1.123 我的订单 -->
<div class="mylogin">
<span>|</span>
<a href="">我的购物车</a>
<span>|</span>
<a href="">我的订单</a>
</div>
</div>
</div>
</div>
</div>
<!--登录-->
<div class="log" id="lo">
<form id="sub" onsubmit="return run()">
<table class="tab">
<caption >登录</caption>
<tr>
<td>用户名</td>
<td><input type="text" id="userId" onfocus="qing(this)" onblur="nokong(this)"></td>
<td><span id="uspan"></span></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" id="pasId" minlength="6" onfocus="qing(this)" onblur="nokong(this)"></td>
<td><span id="pspan"></span></td>
</tr>
<tr>
<td colspan="3"><input type="submit" id="btn" value="提交" ></td>
</tr>
</table>
</form>
</div>
</body>
</html>
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
js的代码:
var uspan = document.getElementById("uspan");
var pspan = document.getElementById("pspan");
var id = document.getElementById("login");
var id2 = document.getElementById("lo");
var f1=false,f2=false;
function nokong(t) {
if (t.id == "userId") {
if (t.value == "") {
uspan.innerText = "用户名不能为空";
t.borderColor = "red";
} else {
f1 = true;
}
}
if (t.id == "pasId") {
if (t.value == "") {
pspan.innerText = "密码不能为空";
t.borderColor = "red";
} else if (t.value.length < t.minLength) {
pspan.innerText = "密码长度不能小于6";
t.borderColor = "red";
} else {
f2 = true;
}
}
}
function qing(t) {
if (t.id == "userId") {
uspan.innerText = "";
}
if (t.id == "pasId") {
pspan.innerText = "";
t.borderColor = "white";
}
}
function show() {
document.getElementById("userId").value="";
document.getElementById("pasId").value="";
//设置通明度
id.style.opacity=0.2;
//显示登录界面
id2.style.display="block";
}
function run() {
if(f1&&f2){
alert("登录成功");
var unlogin = document.getElementById("unlogin");
//隐藏未登录的标签
unlogin.style.display="none";
//显示登录的标签
var log1 = document.getElementById("inlogin");
log1.style.display="block";
document.getElementById("username").innerText=document.getElementById("userId").value;
//隐藏登录界面
id2.style.display="none";
//设置透明度
id.style.opacity=1;
}
return f1&&f2;
}
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
js运算符测试用例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js</title>
<script type="text/javascript">
function run() {
var st="123";
var num=123;
var nu=null;
alert(typeof (st));
alert(typeof (num));
alert(typeof (nu));
alert(typeof (b));
}
//数组
var arr=[23,25,96];
document.write(arr+"</br>");
//实现字符串和数字的相加
var nums=12;
var s="1";
alert(s*1+nums);
//数组的定义,相同变量只使用最后一次定义的变量
var arr1=[26,36,98,46,78];
arr1=new Array(3);
arr1=new Array(3,5,9,3,78);
document.write(arr1+"<br>");
arr1[5]="sta";
arr1[0]=0;
document.write(arr1+"<br>");
document.write(arr1.length);
//三元运算符
var a=3;
var b=5;
var c=9;
document.write((a>b?b:a)>c?c:((a>b?b:a)));
</script>
</head>
<body>
<input type="button" name="but" value="点击" onclick="run()">
<span id="sid">内容</span>
</body>
<script type="text/javascript">
var sp = document.getElementById("sid");
sp.innerText="<font color='red'>hello1</font>";
//sp.innerHTML="<font color='red'>hello2</font>";
alert(sp.innerText);
</script>
</html>
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
js语法及方法测试用例
var par1="x,y";//参数列表
var par2="var sum; sum=x+y; return sum";//方法体
var add=new Function(par1,par2);
alert(add(25,56));
//匿名方法
document.getElementById().onclick = function () {
alert("123456");
}
//documents中的arguments数组
function arg(x,y,z) {
document.write(arguments.length+"<br>");
for(var i=0;i<arguments.length;i++)
{
document.write(arguments[i]+" ");
}
}
arg(122,26,59);
//if-else
var d=new Date();
var time=d.getHours();
if (time<12){
document.write("<b>Good morning</b>");
}else if (time<=14&&time>=12){
document.write("<b>Good lunch</b>");
}else if(time >14){
document.write("<b>Good evening</b>");
}
//switch
var d=new Date();
var day = d.getDay();
switch (day){
case 5:
document.write("Friday");
break;
case 4:
document.write("Thursday");
break;
case 3:
document.write("Wednesday");
break;
case 2:
document.write("Thuesday");
break;
case 1:
document.write("Monday");
break;
case 6:
document.write("Saturday");
break;
case 7:
document.write("Sunday");
break;
default:
break;
}
//条件运算符 变量名=(条件)?值1:值2
vistor = "pres";
var greeting=(vistor=="PRES")?"Dear President":"Dear";alert(greeting);
//警告框 警告框经常用于确保用户可以得到某些信息。当警告框出现后,用户需要点击确定按钮才能继续进行操作。alert("Good morning");
/*
确认框
确认框用于使用户可以验证或者接受某些信息。
当确认框出现后,用户需要点击确定或者取消按钮才能继续进行操作。
如果用户点击确认,那么返回值为 true。如果用户点击取消,那么返回值为 false。
*/
// var st=confirm("保存页面吗?");
// if (st){
// document.write("保存成功!");
// }
/*
提示框经常用于提示用户在进入页面前输入某个值。
当提示框出现后,用户需要输入某个值,然后点击确认或取消按钮才能继续操纵。
如果用户点击确认,那么返回值为输入的值。如果用户点击取消,那么返回值为 null。
prompt("文本","默认值")
*/
var str =prompt("请输入姓名",null);
document.write(str);
//for..in循环
function aa() {
var x;
var arr = new Array(2);
arr[0] = "str";
arr[1] = "ss";
for(x in arr)//不仅可以遍历数组的元素,也可以遍历数组的属性
{
document.write(arr[x]+"<br>");
}
}
aa();
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
js在新窗口打开网页和在原有窗口打开网页
function run() {
window.history.go(1);
document.write(location.href+"<br>");
document.write(history.length+"<br>");
location.href="http://www.baidu.com";//本窗口网页跳转
//window.open("http://www.baidu.com");// 另开窗口网页跳转
window.close();
}
function run(t) {
var nu = document.getElementById("n"+t.id).innerText;
var st = document.getElementById("s"+t.id).innerText;
alert(nu+st);
window.opener.document.getElementById("name").value = st;// 返回父窗口的引用
window.opener.document.getElementById("num").value = nu;
window.close();
}
function op() {
window.open("http://localhost:63342/web/html/table.html");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
js中DOM对象的测试用例
//String对象的创建及方法
//String对象的创建
var st = "abc";
var str = new String(" ab c ");
document.write(st+"<br>");
document.write(str+"<br>");
document.write(st.bold()+"<br>");//字体的粗体
document.write(st.fontcolor("yellow")+"<br>");//字体颜色
document.write(st.fontcolor("yellow").bold()+"<br>");//s方法叠加
document.write(st.fontsize(90)+"<br>");//设置字体的大小
document.write(st.italics()+"<br>");//设置字体为斜体
document.write(st.link("http://www.baidu.com")+"<br>");//设置链接
document.write(st+st.sub()+"<br>");//下标
document.write(st+st.sup()+"<br>");//上标
document.write(st.charAt(0)+"<br>");//返回指定位置的字符
document.write(st.indexOf("bc",1)+"<br>");//获取指定字符串的位置
document.write(st.lastIndexOf("bc",0)+"<br>");//从后向前检索指定字符串的位置
document.write(st.replace("bc","aghl")+"<br>");//替换指定的字符串
document.write(st.substring(1,st.length-1)+"<br>");//获取指定范围的字符串
document.write(st.substr(1,8)+"<br>");//获取指定范围的字符串
document.write(str.trim());
//Date对象
var date1 = new Date();
document.write(date1.toLocaleString()+"<br>");
document.write(date1.toLocaleDateString()+"<br>");
document.write(date1.toLocaleTimeString()+"<br>");
document.write(date1.getTime()+"<br>");
document.write(date1.getDate()+"<br>");
document.write(date1.getDay()+"<br>");
document.write(date1.getHours()+"<br>");
document.write(date1.getMonth()+"<br>");
document.write(date1.getFullYear()+"<br>");
document.write(date1.setTime(123684415648)+"<br>");
document.write(new Date(date1.setTime(date1.getTime())).toLocaleString()+"<br>");
document.write(new Date(Date.parse(date1.toLocaleDateString())).toString()+"<br>");
//Math静态方法
document.write(Math.ceil(12.36522)+"<br>");
document.write(Math.floor(12.6489)+"<br>");
document.write(Math.abs(-45897)+"<br>");
document.write(Math.round(154896156.364)+"<br>");
document.write(Math.round(154896156.564)+"<br>");
document.write(Math.random(15)*10+"<br>");
document.write(Math.random(15)*10+"<br>");
//正则表达式
var reg = new RegExp("");
var reg1 = /^$/;
//全局函数
var st = "alert('369')";
eval(st);
var st1 = "123set";
document.write(isNaN(st1)+"<br>");//isNaN()判断是否是非数字值
var st2 = "123.5";
document.write(parseInt(st2)+"<br>");//将string类型的数字转换为int型,类似的还有parseFloat
var sln = encodeURI("http://www.cnblogs.com/season-huang/some other thing");//encodeURI():将非字母、数字 字符转换成ASCII码,以16进制表示
document.write(sln+"<br>");
document.write(decodeURI(sln)+"<br>");
var sln1 = encodeURIComponent("http://www.cnblogs.com/season-huang/some other thing");
document.write(sln1+"<br>");
document.write(decodeURIComponent(sln1)+"<br>");
var sln2 = escape("张三");
document.write(sln2+"<br>");
document.write(unescape(sln2)+"<br>");
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById("txt").innerHTML=h+":"+m+":"+s;
t = setTimeout("startTime()",500);
}
function checkTime(i) {
if(i<10){
i = "0"+i;
}
return i;
}
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
DOM的测试用例
function run() {
//var id = document.getElementById("spanId");
var id = document.getElementsByTagName("span");
var val = id[0].firstChild.nodeValue ;
alert(val);
}
function add() {
var uId = document.getElementById("uId");
var l4 = document.createElement("li");
var text = document.createTextNode("789");
l4.appendChild(text);
uId.appendChild(l4);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
列表框移动、添加、删除
HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style type="text/css">
* { margin:0; padding:0; }
div.centent {
float:left;
text-align: center;
margin: 10px;
}
span {
display:block;
margin:2px 2px;
padding:4px 10px;
background:#898989;
cursor:pointer;
font-size:12px;
color:white;
}
</style>
</head>
<body>
<div class="centent">
<select multiple="multiple" id="select1" style="width:100px;height:160px;">
<option value="1">选项1</option>
<option value="2">选项2</option>
<option value="3">选项3</option>
<option value="4">选项4</option>
<option value="5">选项5</option>
<option value="6">选项6</option>
<option value="7">选项7</option>
</select>
<div>
<span id="add" onclick="add()">选中添加到右边>></span>
<span id="add_all" onclick="addall()">全部添加到右边>></span>
</div>
</div>
<div class="centent">
<select multiple="multiple" id="select2" style="width: 100px;height:160px;">
<option value="8">选项8</option>
</select>
<div>
<span id="remove" onclick="remove()"><<选中删除到左边</span>
<span id="remove_all" onclick="removeall()"><<全部删除到左边</span>
</div>
</div>
</body>
<script type="text/javascript" src="../js/LieBiaoK.js">
add();
addall();
remove();
removeall();
</script>
</html>
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
js代码
var pid = document.getElementById("select1");
var cid = document.getElementById("select2");
var plist = pid.childNodes;
var clist = cid.childNodes;
function add() {
for(var i=0;i<plist.length;i++){
if(plist[i].selected){
cid.appendChild(plist[i]);
}
}
}
function addall() {
while (pid.hasChildNodes()){
var j=0;
cid.appendChild(plist[j]);
j++;
}
}
function remove() {
for(var i=0;i<clist.length;i++){
if(clist[i].selected){
pid.appendChild(clist[i]);
}
}
}
function removeall() {
while (cid.hasChildNodes()){
var j=0;
pid.appendChild(clist[j]);
j++;
}
}
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
列表框、单选框和多选框被选中的事件
列表框被选中的事件
var pid = document.getElementById("select1");//获取列表框的组件
var cid = document.getElementById("select2");//获取列表框的组件
var plist = pid.childNodes;//获取列表框的选项
var clist = cid.childNodes;//获取列表框的选项
function add() {
for(var i=0;i<plist.length;i++){
if(plist[i].selected){ //判断选项是否被选中
cid.appendChild(plist[i]);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
单选框被选中
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<script type="text/javascript" >
function foo() {
//在此处添加代码
var radio = document.getElementsByName("radioGroup");//获取单选按钮的组件
for(var i=0;i<radio.length;i++)
{
if(radio[i].checked){//判断单选按钮是否被选中
alert("选项"+(i+1)+"被选择");
return true;
}
}
return false;
}
</script>
<body>
<form name="form1" onsubmit="return foo();">
<input type="radio" name="radioGroup"/>
<input type="radio" name="radioGroup"/>
<input type="radio" name="radioGroup"/>
<input type="radio" name="radioGroup"/>
<input type="submit"/>
</form>
</body>
</html>
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
多选框被选中
HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="checkbox" name="group">123<br>
<input type="checkbox" name="group" >456<br>
<input type="checkbox" name="group" >789<br>
<input type="button" id="btn1" onclick="run(this)" value="全选">
<input type="button" id="btn2" onclick="run(this)" value="全不选">
<input type="button" id="btn3" onclick="run(this)" value="反选">
</body>
<script type="text/javascript" src="../js/Xuanze.js">
run(t);
</script>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
js代码
function run(t) {
var group = document.getElementsByName("group");
if(t.id=="btn1"){
for(var i=0;i<group.length;i++){
group[i].checked=true;
}
}else if(t.id=="btn2"){
for(var j=0;j<group.length;j++){
group[j].checked=false;
}
}else if(t.id=="btn3"){
for(var j=0;j<group.length;j++){
if(group[j].checked)
{
group[j].checked=false;
}else if(!group[j].checked){
group[j].checked=true;
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
form递交的代码
HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="success.html" id="sub" onsubmit="return run()">
用户名:<input type="text" id="userId" onfocus="qing(this)" onblur="nokong(this)"><span id="uspan"></span><br>
密码:<input type="password" id="pasId" minlength="6" onfocus="qing(this)" onblur="nokong(this)"><span id="pspan"></span><br>
确认密码:<input type="password" id="repasId" minlength="6" onfocus="qing(this)" onblur="nokong(this)"><span id="repspan"></span><br>
邮箱地址:<input type="email" id="emailId" onfocus="qing(this)" onblur="check(this)"><span id="espan"></span><br>
<input type="submit" id="btn" value="提交" >
</form>
</body>
<script type="text/javascript" src="../js/submitform.js"></script>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
js的代码
var uspan = document.getElementById("uspan");
var pspan = document.getElementById("pspan");
var repspan = document.getElementById("repspan");
var espan = document.getElementById("espan");
var f1=false,f2=false,f3=false;
var flag = false;
function nokong(t) {
var flag = false;
if(t.id=="userId")
{
if(t.value==""){
uspan.innerText="用户名不能为空";
t.borderColor="red";
}else {
f1=true;
}
}
if(t.id=="pasId")
{
if(t.value=="")
{
pspan.innerText="密码不能为空";
t.borderColor="red";
}else if(t.value.length<t.minLength){
pspan.innerText="密码长度不能小于6";
t.borderColor="red";
}else {
f2=true;
}
}
if (t.id=="repasId")
{
var val = document.getElementById("pasId");
if(val.value.length!=t.value.length)
{
repspan.innerText="密码不相等";
t.borderColor="red";
}else if(val.value==t.value){
f3=true;
}
}
return f1&&f2&&f3;
}
function qing(t) {
if(t.id=="userId")
{
uspan.innerText="";
}
if(t.id=="pasId")
{
pspan.innerText="";
t.borderColor="white";
}
if (t.id=="repasId")
{
repspan.innerText="";
t.borderColor="white";
}
if(t.id=="emailId"){
espan.innerText="";
}
}
function check(t) {
if(!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(t.value))
{
espan.innerText="邮箱格式错误";
t.borderColor="red";
}else{
flag = true;
}
return flag;
}
function run() {
return f1&&f2&&f3&&flag;
}
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
省市联动
HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<select id="sheng" onchange="run(this)">
<option value="0" >----请选择省-----</option>
<option value="ah">安徽</option>
<option value="sx">陕西</option>
</select>
<select id="shi">
<option value="0">--请选择市--</option>
</select>
</body>
<script type="text/javascript" src="../js/ShengShi.js">
run(t);
</script>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
js代码:
var id = document.getElementById("shi");
var ah = ["合肥","芜湖"];
var sx = ["西安","咸阳"];
function add(ar) {
for(var i=0;i<ar.length;i++) {
var op = document.createElement("option");
op.innerText = ar[i];
id.appendChild(op);
}
}
function run(t) {
id.options.length=0;
var tishi = document.createElement("option");
tishi.innerText = "--请选择市--";
id.appendChild(tishi);
if(t.value=="ah"){
add(ah);
}else if(t.value == "sx"){
add(sx);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
鼠标事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>css</title>
<!--<script type="text/javascript" src="../js/add.js">-->
<!--</script>-->
<script type="text/javascript" >
var x;
var arr = new Array(2);
arr[0] = "str";
arr[1] = "ss";
for(x in arr)
{
document.write(arr[x]+"<br>");
}
</script>
</head>
<style type="text/css">
/*未访问*/
a:LINK{
text-decoration: none;
color:blue;
}
/*访问*/
a:VISITED{
color: red;
font-size: 40%;
}
/*悬停*/
a:HOVER{
color:yellow;
font-size: 100px;
}
</style>
<body>
<a href="http://www.baidu.com" >百度</a>
</body>
</html>
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
xml的编写实例
<?xml version="1.0" encoding="utf-8"?>
<动物>
<陆地动物 性别="女" 编号="a25">
<猪>动画猪</猪>
<猪>佩奇</猪>
<狗>小黑</狗>
<狗>小白</狗>
</陆地动物>
<海洋动物>
<鱼>鲸鱼</鱼>
<虾>小龙虾</虾>
</海洋动物>
</动物>
1
2
3
4
5
6
7
8
9
10
11
12
13
xml加入DTD约束
<?xml version="1.0" encoding="utf-8"?>
tdd约束
<!DOCTYPE 动物 [
<!ELEMENT 动物 (陆地动物,海洋动物)>
<!ELEMENT 陆地动物 (猪+,狗*,猫?)>
<!ELEMENT 猪 ANY>
<!ELEMENT 狗 (#PCDATA)>
<!ELEMENT 猫 EMPTY>
<!ELEMENT 海洋动物 (鱼,虾)>
<!ELEMENT 鱼 ANY>
<!ELEMENT 虾 (#PCDATA)>
<!ATTLIST 陆地动物
编号 ID #REQUIRED
数量 CDATA #FIXED "123"
性别 (男|女) #IMPLIED>
<!ENTITY 动画猪 "佩奇">
]>
<动物>
<陆地动物 性别="女" 编号="a25">
<猪>动画猪</猪>
<猪>佩奇</猪>
<狗>小黑</狗>
<狗>小白</狗>
</陆地动物>
<海洋动物>
<鱼>鲸鱼</鱼>
<虾>小龙虾</虾>
</海洋动物>
</动物>
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
xml加入schema约束
schema约束文件
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.abc" elementFormDefault="qualified">
<element name="动物">
<complexType>
<sequence>
<element name="陆地动物">
<complexType>
<sequence>
<element name="猪" maxOccurs="4"></element>
<element name="狗" maxOccurs="6"></element>
</sequence>
<attribute name="编号" type="string" use="required"></attribute>
<attribute name="数量" type="int" use="optional"></attribute>
<attribute name="性别" type="string" use="optional"></attribute>
</complexType>
</element>
<element name="海洋动物">
<complexType>
<sequence>
<element name="鱼"></element>
<element name="虾"></element>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>
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
xml的书写
<动物 xmlns="http://www.abc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.abc animal.xsd">
<陆地动物 性别="女" 编号="a25">
<猪>动画猪</猪>
<猪>佩奇</猪>
<狗>小黑</狗>
<狗>小白</狗>
</陆地动物>
<海洋动物>
<鱼>鲸鱼</鱼>
<虾>小龙虾</虾>
</海洋动物>
</动物>
1
2
3
4
5
6
7
8
9
10
11
12
xml的DOM解析
java代码:
package test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import standard.DocuBuildFac;
public class Jiexie {
public static void main(String[] args) {
try {
add();
remove();
edit();
check();
}catch (Exception e){
e.printStackTrace();
}
}
//增加标签
private static void add()throws Exception{
String path = "xml/Animal.xml";
Document doc = DocuBuildFac.getDbfInstane(path);
Element el = doc.createElement("狗");
el.setTextContent("hello");
NodeList ndl = doc.getElementsByTagName("狗");
Node nd = ndl.item(0);
nd.getParentNode().appendChild(el);
DocuBuildFac.reDbfInstane(doc,path);
}
//删除
private static void remove()throws Exception{
String path = "xml/Animal.xml";
Document doc = DocuBuildFac.getDbfInstane(path);
NodeList ndl = doc.getElementsByTagName("狗");
Node nd = ndl.item(0);
nd.getParentNode().removeChild(ndl.item(1));
DocuBuildFac.reDbfInstane(doc,path);
}
//修改
private static void edit()throws Exception{
String path = "xml/Animal.xml";
Document doc = DocuBuildFac.getDbfInstane(path);
NodeList ndl = doc.getElementsByTagName("狗");
ndl.item(1).setTextContent("bye");
DocuBuildFac.reDbfInstane(doc,path);
}
//查看标签
private static void check()throws Exception{
String path = "xml/Animal.xml";
Document doc = DocuBuildFac.getDbfInstane(path);
NodeList ndl = doc.getElementsByTagName("狗");
for(int i=0;i<ndl.getLength();i++){
System.out.println(ndl.item(i).getNodeName()+ndl.item(i).getTextContent());
}
}
}
package standard;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
public class DocuBuildFac {
//获取xml的document的对象
public static Document getDbfInstane(String path) throws Exception{
//获取document工厂接口
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//获取document的建立类
DocumentBuilder db = dbf.newDocumentBuilder();
//建立document
Document doc =db.parse(path);
return doc;
}
//回写xml的方法
public static void reDbfInstane(Document doc,String path) throws Exception{
//获取回写xml的接口
TransformerFactory tff = TransformerFactory.newInstance();
//获取回写xml的类
Transformer tf = tff.newTransformer();
//封装document的源和xml的路径
tf.transform(new DOMSource(doc),new StreamResult(path));
}
}
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
104
105
106
107
xml的SAX解析
package test;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class SAXTest {
public static void main(String[] args) {
try{
run1();
}catch (Exception e){
e.printStackTrace();
}
}
private static void run1() throws Exception {
String path = "xml/Animal.xml";
SAXParserFactory spp = SAXParserFactory.newInstance();
SAXParser sp = spp.newSAXParser();
sp.parse(path,new SAXHandler());
}
}
class SAXHandler extends DefaultHandler{
@Override
//uri:
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if(qName.equals("陆地动物")){
System.out.println("开始解析--"+qName);
for(int i=0;i<attributes.getLength();i++){
System.out.println("陆地动物"+(i+1)+"个属性的属性名:"+attributes.getQName(i));
System.out.println("属性值:"+attributes.getValue(i));
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
if(qName.equals("陆地动物")){
System.out.println("---结束解析---");
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
String st = new String(ch,start,length);
if(st.equals("陆地动物")) {
System.out.println(st);
}
}
}
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
xml的DOM4j解析 (xml带有命名空间)
package test;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import standard.Dom4jSAXMethod;
import java.util.Iterator;
import java.util.List;
public class Dom4jSAXTest {
private static String tagName = "狗";
private static String path = "xml/Animal.xml";
public static void main(String[] args) {
try {
add(path);
delete(path);
edit(path);
check(path);
} catch (Exception e) {
e.printStackTrace();
}
}
//查找标签
private static void check(String path) throws Exception {
Document doc = Dom4jSAXMethod.link(path);
List<Element> list = Dom4jSAXMethod.getxPath(doc,tagName).selectNodes(doc);
Iterator<Element> it = list.iterator();
while (it.hasNext()){
System.out.println(it.next().getText());
}
}
//增加标签
private static void add(String path) throws Exception {
Document doc = Dom4jSAXMethod.link(path);
List<Element> list = Dom4jSAXMethod.getxPath(doc,tagName).selectNodes(doc);
//List<Element> list = doc.selectNodes("//狗"); //xml没有命名空间
Element root = list.get(0).getParent();
Element el = root.addElement("狗");
el.setText("小白");
Dom4jSAXMethod.rewrite(doc,path);
}
//删除标签
private static void delete(String path)throws Exception{
Document doc = Dom4jSAXMethod.link(path);
Node el = Dom4jSAXMethod.getxPath(doc,tagName).selectSingleNode(doc);//tagName表示要删除的标签名
Element parent = el.getParent();
parent.remove(el);
Dom4jSAXMethod.rewrite(doc,path);
}
//修改标签
private static void edit(String path)throws Exception{
Document doc = Dom4jSAXMethod.link(path);
Node el = Dom4jSAXMethod.getxPath(doc,tagName).selectSingleNode(doc);//tagName表示要删除的标签名
el.setText("小黑");
Dom4jSAXMethod.rewrite(doc,path);
}
}
package standard;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.XPath;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
public class Dom4jSAXMethod {
//
public static Document link(String path) throws DocumentException {
SAXReader sr = new SAXReader();
return sr.read(new File(path));
}
//回写
public static void rewrite(Document doc,String path) throws Exception {
OutputFormat opf = OutputFormat.createPrettyPrint();
opf.setEncoding("utf-8");
XMLWriter wr = new XMLWriter(new FileWriter(path),opf);
wr.write(doc);
wr.close();
}
//dom4j获取有命名空间的xml的节点
public static XPath getxPath(Document doc, String tagName) throws Exception {
String namespace = doc.getRootElement().getNamespaceURI();//获取命名空间
HashMap trMap = new HashMap();
trMap.put("root",namespace);
//设置要查找节点的Xpath,并设置该节点的命名空间
XPath xp = doc.createXPath("//root:"+tagName);
xp.setNamespaceURIs(trMap);
return xp;
}
}
前端代码集锦
最新推荐文章于 2023-07-06 13:19:41 发布