前端代码集锦

HTML中隐藏标签和显示标签的例子

注意登录前后的变化
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>

<div id="login">
<div class="login">
    
    <div class="loginbox">
        
        <h3>欢迎您来天天生鲜!h3>
        
        <div class="loginrg">
            
            <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>

            
            <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>

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;
}

js运算符测试用例


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jstitle>
    <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+"
"
); //实现字符串和数字的相加 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+"
"
); arr1[5]="sta"; arr1[0]=0; document.write(arr1+"
"
); 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="hello1"; //sp.innerHTML="hello2"; alert(sp.innerText); script> html>

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+"
"
); 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("Good morning"); }else if (time<=14&&time>=12){ document.write("Good lunch"); }else if(time >14){ document.write("Good evening"); } //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]+"
"
); } } aa();

js在新窗口打开网页和在原有窗口打开网页

function run() {
    window.history.go(1);
    document.write(location.href+"
"
); document.write(history.length+"
"
); 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"); }

js中DOM对象的测试用例

//String对象的创建及方法
//String对象的创建
var st = "abc";
var str = new String("    ab  c        ");
document.write(st+"
"
); document.write(str+"
"
); document.write(st.bold()+"
"
);//字体的粗体 document.write(st.fontcolor("yellow")+"
"
);//字体颜色 document.write(st.fontcolor("yellow").bold()+"
"
);//s方法叠加 document.write(st.fontsize(90)+"
"
);//设置字体的大小 document.write(st.italics()+"
"
);//设置字体为斜体 document.write(st.link("http://www.baidu.com")+"
"
);//设置链接 document.write(st+st.sub()+"
"
);//下标 document.write(st+st.sup()+"
"
);//上标 document.write(st.charAt(0)+"
"
);//返回指定位置的字符 document.write(st.indexOf("bc",1)+"
"
);//获取指定字符串的位置 document.write(st.lastIndexOf("bc",0)+"
"
);//从后向前检索指定字符串的位置 document.write(st.replace("bc","aghl")+"
"
);//替换指定的字符串 document.write(st.substring(1,st.length-1)+"
"
);//获取指定范围的字符串 document.write(st.substr(1,8)+"
"
);//获取指定范围的字符串 document.write(str.trim()); //Date对象 var date1 = new Date(); document.write(date1.toLocaleString()+"
"
); document.write(date1.toLocaleDateString()+"
"
); document.write(date1.toLocaleTimeString()+"
"
); document.write(date1.getTime()+"
"
); document.write(date1.getDate()+"
"
); document.write(date1.getDay()+"
"
); document.write(date1.getHours()+"
"
); document.write(date1.getMonth()+"
"
); document.write(date1.getFullYear()+"
"
); document.write(date1.setTime(123684415648)+"
"
); document.write(new Date(date1.setTime(date1.getTime())).toLocaleString()+"
"
); document.write(new Date(Date.parse(date1.toLocaleDateString())).toString()+"
"
); //Math静态方法 document.write(Math.ceil(12.36522)+"
"
); document.write(Math.floor(12.6489)+"
"
); document.write(Math.abs(-45897)+"
"
); document.write(Math.round(154896156.364)+"
"
); document.write(Math.round(154896156.564)+"
"
); document.write(Math.random(15)*10+"
"
); document.write(Math.random(15)*10+"
"
); //正则表达式 var reg = new RegExp(""); var reg1 = /^$/; //全局函数 var st = "alert('369')"; eval(st); var st1 = "123set"; document.write(isNaN(st1)+"
"
);//isNaN()判断是否是非数字值 var st2 = "123.5"; document.write(parseInt(st2)+"
"
);//将string类型的数字转换为int型,类似的还有parseFloat var sln = encodeURI("http://www.cnblogs.com/season-huang/some other thing");//encodeURI():将非字母、数字 字符转换成ASCII码,以16进制表示 document.write(sln+"
"
); document.write(decodeURI(sln)+"
"
); var sln1 = encodeURIComponent("http://www.cnblogs.com/season-huang/some other thing"); document.write(sln1+"
"
); document.write(decodeURIComponent(sln1)+"
"
); var sln2 = escape("张三"); document.write(sln2+"
"
); document.write(unescape(sln2)+"
"
); 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; }

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);
}

列表框移动、添加、删除

HTML代码


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
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">选项1option>
        <option value="2">选项2option>
        <option value="3">选项3option>
        <option value="4">选项4option>
        <option value="5">选项5option>
        <option value="6">选项6option>
        <option value="7">选项7option>
    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">选项8option>
    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>

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;iif(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;iif(clist[i].selected){
            pid.appendChild(clist[i]);
        }
    }
}

function removeall() {
    while (cid.hasChildNodes()){
        var j=0;
        pid.appendChild(clist[j]);
        j++;
    }
}

列表框、单选框和多选框被选中的事件

列表框被选中的事件

var pid = document.getElementById("select1");//获取列表框的组件
var cid = document.getElementById("select2");//获取列表框的组件
var plist = pid.childNodes;//获取列表框的选项
var clist = cid.childNodes;//获取列表框的选项
function add() {
    for(var i=0;iif(plist[i].selected){  //判断选项是否被选中
            cid.appendChild(plist[i]);
        }
    }
}

单选框被选中

        <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;iif(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>

多选框被选中
HTML代码


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
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>

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;
            }
        }
    }
}

form递交的代码

HTML代码


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
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>

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"密码长度不能小于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;
}

省市联动

HTML代码:


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
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>

js代码:

var id = document.getElementById("shi");
var ah =  ["合肥","芜湖"];
var sx =  ["西安","咸阳"];

function add(ar) {
    for(var i=0;ivar 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);
    }
}

鼠标事件


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>csstitle>
    
    
    <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]+"
"
); }
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>

xml的编写实例


<动物>
<陆地动物 性别="女" 编号="a25"> 
    <>动画猪>  
    <>佩奇>  
    <>小黑>  
    <>小白> 
  陆地动物>  
  <海洋动物> 
    <>鲸鱼>  
    <>小龙虾> 
  海洋动物> 
动物>

xml加入DTD约束


tdd约束










]>
<动物>
<陆地动物 性别="女" 编号="a25"> 
    <>动画猪>  
    <>佩奇>  
    <>小黑>  
    <>小白> 
  陆地动物>  
  <海洋动物> 
    <>鲸鱼>  
    <>小龙虾> 
  海洋动物> 
动物>

xml加入schema约束

schema约束文件


<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>

xml的书写

<动物 xmlns="http://www.abc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.abc animal.xsd">  
  <陆地动物 性别="女" 编号="a25"> 
    <>动画猪>  
    <>佩奇>  
    <>小黑>  
    <>小白> 
  陆地动物>  
  <海洋动物> 
    <>鲸鱼>  
    <>小龙虾> 
  海洋动物> 
动物>

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;ipackage 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));
    }
}

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"陆地动物"+(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);
        }
    }
}

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 list = Dom4jSAXMethod.getxPath(doc,tagName).selectNodes(doc);
        Iterator 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 list = Dom4jSAXMethod.getxPath(doc,tagName).selectNodes(doc);
        //List 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;
    }
}

你可能感兴趣的:(前端)