第3篇  XML篇
第10章  初识XML
10.1  XML语言基础
实例297  简单的XML
<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <name>JAVA范例完全自学手册</name>
        <publisher>人民邮电出版社</publisher>
        <author>李钟尉</author>
        <ISBN>9787115201027</ISBN>
        <price>59.80</price>
    </book>
</books>

实例298  验证XML的格式
<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <name>JAVA范例完全自学手册</name>
        <publisher>人民邮电出版社</publisher>
        <author>李钟尉</author>
        <ISBN>9787115201027</ISBN>
        <price>59.80</price>
</books>

实例299  XML属性的使用
<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <name>C#从入门到精通(第2版) </name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
    </book>
    <book>
        <name>JavaScript开发技术大全</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
    </book>
</books>

实例300  XML中CDATA的使用
<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <name>C#从入门到精通(第2版) </name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>JavaScript开发技术大全</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>Java全能速查宝典</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>视频学Java Web(1DVD)</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>

10.2  XML与CSS
实例301  在XML中使用CSS
demo.css
books
{
    background-color: #FFFFFF;
    width: 100%;
}

book
{
    display: block;
    margin-bottom: 25pt;
    margin-left: 0;
}

name
{
    color: #FF0000;
    font-size: 20pt;
}

publisher
{
    color: #3333FF;
    font-size: 20pt;
}

company,author,isbn,price,url
{
    display: block;
    color: #000000;
    margin-left: 20pt;
}

demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="simple_demo.css"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>

实例302  CSS格式化XML布局
demo.css
book
{
    display: block;
}

name
{
    display: block;
}

publisher,company,author,ISBN,price,url
{
    display: inline;
}
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="display_demo.css"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>

实例303  CSS格式化XML背景色
demo.css
book
{
    display: block;
}

name
{
    display: block;
}

publisher,company,author,ISBN,price,url
{
    display: inline;
}

book
{
    background-color: #3F0;
}

name
{
    background-color: #1CC;
}

publisher
{
    background-color: #CC9999;
}

company,author,isbn,price,url
{
    background-color: #CCCCFF;
}

demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="background_demo.css"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>

实例304  CSS格式化XML字体
demo.css
book
{
    display: block;
    font-size: 15px
}

name
{
    display: block;
    font-size: 30px;
    font-style: italic;
}

publisher{
    display: inline;
    font-size: 24px;
    text-decoration: underline;
}
company,author,ISBN,price,url
{
    display: inline;
}
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="background_demo.css"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>

实例305  CSS改变XML中的鼠标手势
demo.css
book
{
    display: block;
}

name
{
    display: block;
}

publisher
{
    display: block;
}
company,author,ISBN,price,url
{
    display: inline;
}

name
{
    cursor:crosshair;
}

publisher
{
    cursor:hand;
}

company,author,isbn,price,url
{
    cursor:wait;
}

demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="cursor_demo.css"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>

实例306  CSS在XML中添加背景图
demo.css
book
{
    display: block;
}

name
{
    display: block;
}

publisher,company,author,ISBN,price,url
{
    display: inline;
}
pic
{
    background-image: url(background-image_demo.jpg);
    width:153px;
    height:193px;
}
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="background-image_demo.css"?>
<books>
    <book>
        <pic></pic>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>

实例307  CSS制作XML表格
demo.css
book
{
    display: block;
    border-width: 1px;
    border-color: #930;
    border-style:outset;
    background-color: #CCC
}
name
{
    display: block;
    text-align: center;
}
publisher,company,author,ISBN,price
{
    text-align: center;
    width: 18%
}
url
{
    display: block;
}
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="table_demo.css"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <author>王小科</author>
        <company>明日科技</company>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>
10.3  XML与XSLT的元素
实例308  在XML中使用XSLT
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="simple_demo.xsl"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>
demo.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
 <body>
   <h2 align="center">我喜欢的图书</h2>
   <table border="1">
     <tr bgcolor="#55A0FF">
       <th>名称</th>
       <th>出版社</th>
       <th>公司</th>
       <th>作者</th>
       <th>ISBN</th>
       <th>价格</th>
     </tr>
     <xsl:for-each select="books/book">
     <xsl:sort select="price"/>
     <tr>
       <td><xsl:value-of select="name"/></td>
       <td><xsl:value-of select="publisher"/></td>
       <td><xsl:value-of select="company"/></td>
       <td><xsl:value-of select="author"/></td>
       <td><xsl:value-of select="ISBN"/></td>
       <td><xsl:value-of select="price"/></td>
     </tr>
     <tr>
       <th bgcolor="#55A0FF" align="center">网站地址</th>
       <td colspan="5"><xsl:value-of select="url"/></td>
     </tr>
     </xsl:for-each>
   </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

实例309  使用XSLT中的template
demo.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
 <body>
   <table border="1">
     <tr bgcolor="#55A0FF">
       <th>名称</th>
       <th>出版社</th>
       <th>公司</th>
       <th>作者</th>
       <th>ISBN</th>
       <th>价格</th>
     </tr>
     <tr>
       <td>.</td>
       <td>.</td>
       <td>.</td>
       <td>.</td>
       <td>.</td>
       <td>.</td>
     </tr>
   </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="template_demo.xsl"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>

实例310  使用XSLT中的value-of
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="value-of_demo.xsl"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
</books>
demo.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
 <body>
   <table border="1">
     <tr>
       <td><xsl:value-of select="books/book/name"/></td>
       <td><xsl:value-of select="books/book/publisher"/></td>
       <td><xsl:value-of select="books/book/company"/></td>
       <td><xsl:value-of select="books/book/author"/></td>
       <td><xsl:value-of select="books/book/ISBN"/></td>
       <td><xsl:value-of select="books/book/price"/></td>
     </tr>
   </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

实例311  使用XSLT中的for-each
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="for-each_demo.xsl"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>
demo.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
 <body>
   <table border="1">
   <xsl:for-each select="books/book">
     <tr>
       <td><xsl:value-of select="name"/></td>
       <td><xsl:value-of select="publisher"/></td>
       <td><xsl:value-of select="company"/></td>
       <td><xsl:value-of select="author"/></td>
       <td><xsl:value-of select="ISBN"/></td>
       <td><xsl:value-of select="price"/></td>
     </tr>
    </xsl:for-each>
   </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

实例312  使用XSLT中的if
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="if_demo.xsl"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>
demo.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
 <body>
   <table border="1">
     <tr>
       <td>名称</td>
       <td>出版社</td>
       <td>出版公司</td>
       <td>作者</td>
       <td>ISBN号</td>
       <td>价格</td>
     </tr>
   <xsl:for-each select="books/book">
    <xsl:if test="author = '梁冰'">
         <tr bgcolor="#7D7DFF">
           <td><xsl:value-of select="name"/></td>
           <td><xsl:value-of select="publisher"/></td>
           <td><xsl:value-of select="company"/></td>
           <td><xsl:value-of select="author"/></td>
           <td><xsl:value-of select="ISBN"/></td>
           <td><xsl:value-of select="price"/></td>
         </tr>
     </xsl:if>
    <xsl:if test="author != '梁冰'">
         <tr bgcolor="#FFFF6F">
           <td><xsl:value-of select="name"/></td>
           <td><xsl:value-of select="publisher"/></td>
           <td><xsl:value-of select="company"/></td>
           <td><xsl:value-of select="author"/></td>
           <td><xsl:value-of select="ISBN"/></td>
           <td><xsl:value-of select="price"/></td>
         </tr>
     </xsl:if>
    </xsl:for-each>
   </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

实例313  使用XSLT中的sort
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="sort_demo.xsl"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>
demo.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
 <body>
   <table>
     <tr bgcolor="#8E8E8E">
       <td>名称</td>
       <td>出版社</td>
       <td>出版公司</td>
       <td>作者</td>
       <td>ISBN号</td>
       <td>价格</td>
     </tr>
   <xsl:for-each select="books/book">
       <xsl:sort select="price" order="descending" />
     <tr bgcolor="#C2C287">
       <td><xsl:value-of select="name"/></td>
       <td><xsl:value-of select="publisher"/></td>
       <td><xsl:value-of select="company"/></td>
       <td><xsl:value-of select="author"/></td>
       <td><xsl:value-of select="ISBN"/></td>
       <td><xsl:value-of select="price"/></td>
     </tr>
    </xsl:for-each>
   </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

实例314  使用XSLT中的choose
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="choose_demo.xsl"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>
demo.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
 <body>
   <table>
     <tr bgcolor="#8E8E8E">
       <td>名称</td>
       <td>出版社</td>
       <td>出版公司</td>
       <td>作者</td>
       <td>ISBN号</td>
       <td>价格</td>
     </tr>
   <xsl:for-each select="books/book">
       <xsl:choose>
       <xsl:when test="(price &lt; 50)">
         <tr bgcolor="#CDCD9A">
           <td><xsl:value-of select="name"/></td>
           <td><xsl:value-of select="publisher"/></td>
           <td><xsl:value-of select="company"/></td>
           <td><xsl:value-of select="author"/></td>
           <td><xsl:value-of select="ISBN"/></td>
           <td><xsl:value-of select="price"/></td>
         </tr>
       </xsl:when>
       <xsl:when test="(price &lt;= 65)" >
         <tr bgcolor="#A5A552">
           <td><xsl:value-of select="name"/></td>
           <td><xsl:value-of select="publisher"/></td>
           <td><xsl:value-of select="company"/></td>
           <td><xsl:value-of select="author"/></td>
           <td><xsl:value-of select="ISBN"/></td>
           <td><xsl:value-of select="price"/></td>
         </tr>
       </xsl:when>
        <xsl:otherwise>
         <tr bgcolor="#616130">
           <td><xsl:value-of select="name"/></td>
           <td><xsl:value-of select="publisher"/></td>
           <td><xsl:value-of select="company"/></td>
           <td><xsl:value-of select="author"/></td>
           <td><xsl:value-of select="ISBN"/></td>
           <td><xsl:value-of select="price"/></td>
         </tr>
        </xsl:otherwise>
      </xsl:choose>     
    </xsl:for-each>
   </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

实例315  使用XSLT中的copy-of
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="copy-of_demo.xsl"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>
demo.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:variable name="title">
     <tr bgcolor="#8E8E8E">
       <td>名称</td>
       <td>出版社</td>
       <td>出版公司</td>
       <td>作者</td>
       <td>ISBN号</td>
       <td>价格</td>
     </tr>
</xsl:variable>

<xsl:template match="/">
<html>
 <body>
   <table>
   <xsl:for-each select="books/book">
    <xsl:copy-of select="$title" />
         <tr bgcolor="#CDCD9A">
           <td><xsl:value-of select="name"/></td>
           <td><xsl:value-of select="publisher"/></td>
           <td><xsl:value-of select="company"/></td>
           <td><xsl:value-of select="author"/></td>
           <td><xsl:value-of select="ISBN"/></td>
           <td><xsl:value-of select="price"/></td>
         </tr>
    </xsl:for-each>
   </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

实例316  使用XSLT中的apply-templates
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="apply-templates_demo.xsl"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>
demo.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
 <body>
   <xsl:apply-templates/>
 </body>
 </html>
</xsl:template>

<xsl:template  match="book">
<xsl:apply-templates select="name"/>
<xsl:apply-templates select="ISBN"/>
<xsl:apply-templates select="price"/>
<br/>
</xsl:template>

<xsl:template match="name">
<span style="color:#00008b">名称:<xsl:value-of select="."/></span>
<br/>
</xsl:template>
<xsl:template match="price">
<span style="color:#8b008b">价格: <xsl:value-of select="."/></span>
<br/>
</xsl:template>
<xsl:template match="ISBN">
<span style="color:#2f4f4f">ISBN: <xsl:value-of select="."/></span>
<br/>
</xsl:template>
</xsl:stylesheet>

实例317  使用XSLT中的attribute
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="attribute_demo.xsl"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>

demo.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
 <body>
   <table>
     <tr bgcolor="#8E8E8E">
       <td>名称</td>
       <td>出版社</td>
       <td>出版公司</td>
       <td>作者</td>
       <td>ISBN号</td>
       <td>价格</td>
     </tr>
   <xsl:for-each select="books/book">
     <tr bgcolor="#C2C287">
       <td><xsl:attribute name="title"><xsl:value-of select="name"/></xsl:attribute><xsl:value-of select="name"/></td>
       <td><xsl:value-of select="publisher"/></td>
       <td><xsl:value-of select="company"/></td>
       <td><xsl:value-of select="author"/></td>
       <td><xsl:value-of select="ISBN"/></td>
       <td><xsl:value-of select="price"/></td>
     </tr>
    </xsl:for-each>
   </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

实例318  使用XSLT中的elements
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="element_demo.xsl"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM">6980</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM">6500</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM">5900</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM">4980</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>
demo.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" version="4.0" encoding="iso-8859-1" indent="yes"/>
    
    <xsl:template match="/">
        <html>
            <body>
                <xsl:element name="h2" >
                    我喜欢的图书
                </xsl:element>
               <table>
                 <tr bgcolor="#8E8E8E">
                   <td>名称</td>
                   <td>出版社</td>
                   <td>出版公司</td>
                   <td>作者</td>
                   <td>ISBN号</td>
                   <td>价格</td>
                 </tr>
               <xsl:for-each select="books/book">
                   <xsl:sort select="price" order="descending" />
                 <tr bgcolor="#C2C287">
                   <td><xsl:value-of select="name"/></td>
                   <td><xsl:value-of select="publisher"/></td>
                   <td><xsl:value-of select="company"/></td>
                   <td><xsl:value-of select="author"/></td>
                   <td><xsl:value-of select="ISBN"/></td>
                   <td><xsl:value-of select="price"/></td>
                 </tr>
                </xsl:for-each>
               </table>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

10.4  XML与XSLT的内建函数
实例319  使用XSLT中的generate-id()
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="generate-id_demo.xsl"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM">69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM">65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM">59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM">49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>
demo.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" version="4.0" encoding="iso-8859-1"
        indent="yes" />

<xsl:template match="/">
        <html>
            <body>
                <xsl:element name="h2">
                    我喜欢的图书
                </xsl:element>

<xsl:for-each select="books/book">
                    <p>
                        <xsl:value-of select="name" /> <a href="#{generate-id(name)}">查看详细</a>
                    </p>
                </xsl:for-each>
                    <hr/>
                <xsl:for-each select="books/book">
                    <p>
                        <a name="#{generate-id(name)}"><xsl:value-of select="name" /></a>
                    </p>
                    <p>
                        <xsl:value-of select="publisher" />
                    </p>
                    <p>
                        <xsl:value-of select="company" />
                    </p>
                    <p>
                        <xsl:value-of select="author" />
                    </p>
                    <p>
                        <xsl:value-of select="ISBN" />
                    </p>
                    <p>
                        <xsl:value-of select="price" />
                    </p>
                    <p>
                        <xsl:value-of select="url" />
                    </p>
                    <hr/>
                </xsl:for-each>

</body>
        </html>
    </xsl:template>
</xsl:stylesheet>

实例320  使用XSLT中的format-number()
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="format-number_demo.xsl"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >6980</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >6500</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >5900</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >4980</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>
demo.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
 <body>
   <table>
     <tr bgcolor="#8E8E8E">
       <td>名称</td>
       <td>出版社</td>
       <td>出版公司</td>
       <td>作者</td>
       <td>ISBN号</td>
       <td>价格</td>
     </tr>
   <xsl:for-each select="books/book">
     <tr bgcolor="#C2C287">
       <td><xsl:value-of select="name"/></td>
       <td><xsl:value-of select="publisher"/></td>
       <td><xsl:value-of select="company"/></td>
       <td><xsl:value-of select="author"/></td>
       <td><xsl:value-of select="ISBN"/></td>
       <td><xsl:value-of select='format-number(price,"###,###.00")'/>(分)</td>
     </tr>
    </xsl:for-each>
   </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

实例321  使用XSLT中的document()
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="document_demo.xsl"?>
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book>
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115179708</ISBN>
        <price unit="RBM" >65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book>
        <name>《Java全能速查宝典》</name>
        <publisher>人民邮电出版社</publisher>
        <author>梁冰</author>
        <company>明日科技</company>
        <ISBN>9787115214874</ISBN>
        <price unit="RBM" >59.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=191&sid=7]]></url>
    </book>
    <book>
        <name>《视频学Java Web(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>王国辉</author>
        <company>明日科技</company>
        <ISBN>9787115219893</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=208&sid=11]]></url>
    </book>
</books>

demo.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
 <body>
   <table>
     <tr bgcolor="#8E8E8E">
       <td>名称</td>
       <td>出版社</td>
       <td>出版公司</td>
       <td>作者</td>
       <td>ISBN号</td>
       <td>价格</td>
     </tr>
   <xsl:for-each select="books/book">
     <tr bgcolor="#C2C287">
       <td><xsl:value-of select="name"/></td>
       <td><xsl:value-of select="publisher"/></td>
       <td><xsl:value-of select="company"/></td>
       <td><xsl:value-of select="author"/></td>
       <td><xsl:value-of select="ISBN"/></td>
       <td><xsl:value-of select="price"/></td>
     </tr>
    </xsl:for-each>
   <xsl:for-each select="document('document_ext_demo.xml')/books/book">
     <tr bgcolor="#C2C287">
       <td><xsl:value-of select="name"/></td>
       <td><xsl:value-of select="publisher"/></td>
       <td><xsl:value-of select="company"/></td>
       <td><xsl:value-of select="author"/></td>
       <td><xsl:value-of select="ISBN"/></td>
       <td><xsl:value-of select="price"/></td>
     </tr>
    </xsl:for-each>
   </table>
 </body>
 </html>
</xsl:template>
</xsl:stylesheet>

ext_demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <name>《视频学C语言》</name>
        <publisher>人民邮电出版社</publisher>
        <company>明日科技</company>
        <author>李伟明</author>
        <ISBN>9787115220660</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo-207.html]]></url>
    </book>
    <book>
        <name>《视频学ASP.NET(1DVD)》</name>
        <publisher>人民邮电出版社</publisher>
        <author>房大伟</author>
        <company>明日科技</company>
        <ISBN>9787115218698</ISBN>
        <price unit="RBM" >49.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo-210.html]]></url>
    </book>
    <book>
        <name>《PHP从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <author>潘凯华</author>
        <company>明日科技</company>
        <ISBN>9787302227472</ISBN>
        <price unit="RBM" >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo-223.html]]></url>
    </book>
    
</books>

10.5  DTD的引用与验证
实例322  在XML内部定义DTD
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE  book [
    <!ELEMENT book (name,publisher,company,author,ISBN,price,url)>
    <!ELEMENT name      (#PCDATA)>
    <!ELEMENT publisher    (#PCDATA)>
    <!ELEMENT company (#PCDATA)>
    <!ELEMENT author    (#PCDATA)>
    <!ELEMENT ISBN    (#PCDATA)>
    <!ELEMENT price    (#PCDATA)>
    <!ELEMENT url    (#PCDATA)>
]>
<book>
    <name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>

实例323  在XML外部引用DTD
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT book (name,publisher,company,author,ISBN,price,url)>
<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book SYSTEM "simple_demo.dtd">
<book>
    <name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>

实例324  验证XML是否符合DTD的定义
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT book (name,publisher,company,author,ISBN,price,url)>
<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book SYSTEM "simple_demo.dtd">
<book>
    <name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>

10.6  使用DTD定义XML元素
实例325  在DTD中声明元素
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT book (name,publisher,company,author,ISBN,price,url)>
<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book SYSTEM "simple_demo.dtd">
<book>
    <name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>

实例326  在DTD中声明重复元素
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book SYSTEM "author_demo.dtd">
<book>
    <name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <author>徐薇</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>
demo.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT book (name,publisher,company,author+,ISBN,price,url)>
<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>

实例327  在DTD中声明选择性元素
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book SYSTEM "tel_demo.dtd">
<book>
    <name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    <tel>13812345678</tel>
</book>
demo.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT book (name,publisher,company,author,ISBN,price,url,(tel|phone))>
<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>
<!ELEMENT tel    (#PCDATA)>
<!ELEMENT phone    (#PCDATA)>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

实例328  在DTD中使用ENTITY
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT books (book+)>
<!ELEMENT book    (name,publisher,company,author,ISBN,price,url,type)>
<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company     (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>
<!ELEMENT type    (#PCDATA)>
<!ENTITY info "软件工程师入门丛书" >
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books SYSTEM "entity_demo.dtd">
<books>

<book>
        <name>《Java从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>李钟蔚</author>
        <ISBN>9787302227465</ISBN>
        <price>59.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=222]]></url>
        <type>&info;</type>
    </book>
</books>

10.7  使用DTD定义XML属性
实例329  在DTD中声明元素属性
demo.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT book (name,publisher,company,author,ISBN,price,url)>
<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company     (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>
<!ATTLIST price unit CDATA "RMB" >
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book SYSTEM "attlist_demo.dtd">
<book>
    <name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

实例330  在DTD中声明带有#IMPLIED的属性
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book SYSTEM "attlist_implied_demo.dtd">
<book>
    <name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price unit="RMB">69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>
demo.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT book (name,publisher,company,author,ISBN,price,url)>
<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company     (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>
<!ATTLIST price unit CDATA  #IMPLIED >

实例331  在DTD中声明带有#REQUIRED的属性
demo.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT book (name,publisher,company,author,ISBN,price,url)>
<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company     (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>
<!ATTLIST price unit CDATA #REQUIRED>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book SYSTEM "attlist_required_demo.dtd">
<book>
    <name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price unit="RMB">69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

实例332  在DTD中声明带有#FIXED的属性
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book SYSTEM "attlist_fixed_demo.dtd">
<book>
    <name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price unit="RMB">69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>
demo.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT book (name,publisher,company,author,ISBN,price,url)>
<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company     (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>
<!ATTLIST price unit CDATA #FIXED "RMB">

实例333  在DTD中声明列举属性值
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book SYSTEM "attlist_many_demo.dtd">
<book>
    <name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price unit="元" >69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>
demo.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT book (name,publisher,company,author,ISBN,price,url)>
<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company     (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>
<!ATTLIST price unit (元|角|分) "元">

实例334  类型为ID的属性实例
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books SYSTEM "attlist_id_demo.dtd">
<books>
    <book UID="AAAA">
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book UID="AAAB">
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <company>明日科技</company>
        <author>梁冰</author>
        <ISBN>9787115179708</ISBN>
        <price>65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
</books>
demo.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT books (book+)>

<!ELEMENT book    (name,publisher,company,author,ISBN,price,url)>

<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company     (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>
<!ATTLIST book UID ID #REQUIRED>

实例335  类型为IDREF的属性实例
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books SYSTEM "attlist_idref_demo.dtd">
<books>
    <book UID="AAAA">
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price >69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
    <book UID="AAAB">
        <name>《JavaScript开发技术大全》</name>
        <publisher>人民邮电出版社</publisher>
        <company>明日科技</company>
        <author>梁冰</author>
        <ISBN>9787115179708</ISBN>
        <price>65.00</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=138&sid=5]]></url>
    </book>
    <book UID="AAAC">
        <name>《Java从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>李钟蔚</author>
        <ISBN>9787302227465</ISBN>
        <price>59.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=222]]></url>
        <relevance relUID="AAAA">《C#从入门到精通(第2版)》</relevance>
    </book>
</books>
demo.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT books (book+)>

<!ELEMENT book    (name,publisher,company,author,ISBN,price,url,relevance*)>

<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company     (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>
<!ELEMENT relevance    (#PCDATA)>
<!ATTLIST book UID ID #REQUIRED>
<!ATTLIST relevance relUID IDREF #REQUIRED>

实例336  类型为NMTOKEN的属性实例
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过DTD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books SYSTEM "attlist_nmtoken_demo.dtd">
<books>
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price unit="RMB">69.80</price>
        <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    </book>
</books>
demo.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT books (book+)>

<!ELEMENT book    (name,publisher,company,author,ISBN,price,url)>

<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company     (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>
<!ATTLIST price unit NMTOKEN #REQUIRED>

第11章  XML Schema
11.1  XSD的引用与验证
实例337  在XML中使用XML Schema
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book" type="bookType" />

<xs:complexType name="bookType">
        <xs:sequence>
            <xs:element name="name" type="xs:string" />
            <xs:element name="publisher" type="xs:string" />
            <xs:element name="company" type="xs:string" />
            <xs:element name="author" type="xs:string" />
            <xs:element name="ISBN" type="xs:string" />
            <xs:element name="price" type="xs:string" />
            <xs:element name="url" type="xs:string" />
        </xs:sequence>
    </xs:complexType>
</xs:schema>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
        xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com simple_demo.xsd">

<name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>

实例338  验证XML是否符合Schema的描述
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com simple_demo.xsd">

<name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book" type="bookType" />

<xs:complexType name="bookType">
        <xs:sequence>
            <xs:element name="name" type="xs:string" />
            <xs:element name="publisher" type="xs:string" />
            <xs:element name="company" type="xs:string" />
            <xs:element name="author" type="xs:string" />
            <xs:element name="ISBN" type="xs:string" />
            <xs:element name="price" type="xs:string" />
            <xs:element name="url" type="xs:string" />
        </xs:sequence>
    </xs:complexType>
</xs:schema>

实例339  XSD文档根元素的引用
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">
</xs:schema>

实例340  在XSD中使用注释
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com simple_demo.xsd">
</book>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">
    <xs:annotation>
        <xs:documentation>这是一个图书的数据结构,定义了图书的基本信息</xs:documentation>
    </xs:annotation>
</xs:schema>

11.2  使用XSD简单类型定义XML元素
实例341  在XSD中定义XML元素
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com element_demo.xsd">明日科技图书</book>
<xml>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">
    <xs:element name="book" type="xs:string" fixed="明日科技图书"></xs:element>
</xs:schema>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

实例342  使用xs:simpleType和xs:restriction
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com simpleType_demo.xsd">123456666</book>
<xml>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book">
        <xs:simpleType>
            <xs:restriction base="xs:string">
            <xs:maxLength value="5"></xs:maxLength>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
</xs:schema>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

实例343  使用xs:list
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com list_demo.xsd">

<name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80 69.00</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="name" type="xs:string" />
                <xs:element name="publisher" type="xs:string" />
                <xs:element name="company" type="xs:string" />
                <xs:element name="author" type="xs:string" />
                <xs:element name="ISBN" type="xs:string" />
                <xs:element name="price">
                    <xs:simpleType>
                        <xs:restriction base="pricetype">
                            <xs:maxLength value="2"></xs:maxLength>
                        </xs:restriction>
                    </xs:simpleType>
                </xs:element>
                <xs:element name="url" type="xs:string" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    
    <xs:simpleType name="pricetype">
        <xs:list itemType="xs:double"></xs:list>
    </xs:simpleType>
</xs:schema>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

实例344  使用xs:enumeration
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com enumeration_demo.xsd">

<name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80 69.00</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="name" type="xs:string" />
                <xs:element name="publisher" type="xs:string" />
                <xs:element name="company" type="xs:string" />
                <xs:element name="author">
                    <xs:simpleType>
                        <xs:restriction base="xs:string">
                            <xs:enumeration value="王小科"></xs:enumeration>
                            <xs:enumeration value="徐薇"></xs:enumeration>
                        </xs:restriction>
                    </xs:simpleType>
                </xs:element>
                <xs:element name="ISBN" type="xs:string" />
                <xs:element name="price">
                    <xs:simpleType>
                        <xs:restriction base="pricetype">
                            <xs:maxLength value="2"></xs:maxLength>
                        </xs:restriction>
                    </xs:simpleType>
                </xs:element>
                <xs:element name="url" type="xs:string" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

<xs:simpleType name="pricetype">
        <xs:list itemType="xs:double"></xs:list>
    </xs:simpleType>
</xs:schema>

实例345  使用xs:pattern
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com pattern_demo.xsd">

<name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>

</book>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book" type="bookType" />

<xs:complexType name="bookType">
        <xs:sequence>
            <xs:element name="name" type="xs:string" />
            <xs:element name="publisher" type="xs:string" />
            <xs:element name="company" type="xs:string" />
            <xs:element name="author" type="xs:string" />
            <xs:element name="ISBN">
                <xs:simpleType>
                    <xs:restriction base="xs:integer">
                        <xs:pattern value="[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]" />
                    </xs:restriction>
                </xs:simpleType>
            </xs:element>
            <xs:element name="price" type="xs:string" />
            <xs:element name="url" type="xs:string" />
        </xs:sequence>
    </xs:complexType>
</xs:schema>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

11.3  使用XSD复杂类型定义XML元素
实例346  使用xs:complexType和xs:sequence
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com complexType_demo.xsd">

<name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80</price>
    <url>http://www.mingribook.com/bookinfo.php?id=227</url>
</book>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="name" type="xs:string" />
                <xs:element name="publisher" type="xs:string" />
                <xs:element name="company" type="xs:string" />
                <xs:element name="author" type="xs:string" />
                <xs:element name="ISBN" type="xs:string" />
                <xs:element name="price" type="xs:double" />
                <xs:element name="url" type="xs:string" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

</xs:schema>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

实例347  使用xs:choice
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com choice_demo.xsd">

<name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <ISBN>9787302226628</ISBN>
    <price>69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book" type="bookType" />

<xs:complexType name="bookType">
        <xs:sequence>
            <xs:element name="name" type="xs:string" />
            <xs:element name="publisher" type="xs:string" />
            <xs:choice>
                <xs:element name="company" type="xs:string" />
                <xs:element name="author" type="xs:string" />
            </xs:choice>
            <xs:element name="ISBN" type="xs:string" />
            <xs:element name="price" type="xs:double" />
            <xs:element name="url" type="xs:string" />
        </xs:sequence>
    </xs:complexType>
</xs:schema>

实例348  使用xs:all
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com all_demo.xsd">

<publisher>清华大学出版社</publisher>
    <name>《C#从入门到精通(第2版)》</name>
    <company>明日科技</company>
    <author>王小科</author>
    <price>69.80</price>
    <ISBN>9787302226628</ISBN>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book" type="bookType" />

<xs:complexType name="bookType">
        <xs:all>
            <xs:element name="name" type="xs:string" />
            <xs:element name="publisher" type="xs:string" />
            <xs:element name="company" type="xs:string" />
            <xs:element name="author" type="xs:string" />
            <xs:element name="ISBN" type="xs:string" />
            <xs:element name="price" type="xs:double" />
            <xs:element name="url" type="xs:string" />
        </xs:all>
    </xs:complexType>
</xs:schema>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

实例349  使用xs:group
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com group_demo.xsd">

<publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
    <name>《C#从入门到精通(第2版)》</name>

</book>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book">
        <xs:complexType>
            <xs:sequence>
                <xs:group ref="otherType"></xs:group>
                <xs:element name="name" type="xs:string" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:group name="otherType">
        <xs:sequence>
            <xs:element name="publisher" type="xs:string" />
            <xs:element name="company" type="xs:string" />
            <xs:element name="author" type="xs:string" />
            <xs:element name="ISBN" type="xs:string" />
            <xs:element name="price" type="xs:double" />
            <xs:element name="url" type="xs:string" />
        </xs:sequence>
    </xs:group>
</xs:schema>

实例350  使用xs:extension和xs:simpleContent
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com extension_demo.xsd">

<name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price RMB="yuan">69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book" type="bookType" />

<xs:complexType name="bookType">
        <xs:sequence>
            <xs:element name="name" type="xs:string" />
            <xs:element name="publisher" type="xs:string" />
            <xs:element name="company" type="xs:string" />
            <xs:element name="author" type="xs:string" />
            <xs:element name="ISBN" type="xs:string" />
            <xs:element name="price">
                <xs:complexType>
                    <xs:simpleContent>
                        <xs:extension base="xs:double">
                            <xs:attribute name="RMB" type="xs:string" use="required"></xs:attribute>
                        </xs:extension>
                    </xs:simpleContent>
                </xs:complexType>
            </xs:element>
            <xs:element name="url" type="xs:string" />
        </xs:sequence>
    </xs:complexType>
</xs:schema>

实例351  使用xs:extension和xs:complexContent
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com extension_complexContent_demo.xsd">

<name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price RMB="yuan">
        <discount>69.00</discount>
        <original>69.80</original>
    </price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="name" type="xs:string" />
                <xs:element name="publisher" type="xs:string" />
                <xs:element name="company" type="xs:string" />
                <xs:element name="author" type="xs:string" />
                <xs:element name="ISBN" type="xs:string" />
                <xs:element name="price">
                    <xs:complexType>
                        <xs:complexContent>
                            <xs:extension base="discountPrice">
                                <xs:sequence>
                                    <xs:element name="original" type="xs:double" />
                                </xs:sequence>
                                <xs:attribute name="RMB" type="xs:string" use="required" />
                            </xs:extension>
                        </xs:complexContent>
                    </xs:complexType>
                </xs:element>
                <xs:element name="url" type="xs:string" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

<xs:complexType name="discountPrice">
        <xs:sequence>
            <xs:element name="discount" type="xs:double" />
        </xs:sequence>
    </xs:complexType>
</xs:schema>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

实例352  使用xs:restriction和xs:simpleContent
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com restriction_simpleContent_demo.xsd">

<name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price RMB="yuan">69.80</price>
    <url>http://www.mingribook.com/bookinfo.php?id=227</url>
</book>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="name" type="xs:string" />
                <xs:element name="publisher" type="xs:string" />
                <xs:element name="company" type="xs:string" />
                <xs:element name="author" type="xs:string" />
                <xs:element name="ISBN" type="xs:string" />
                <xs:element name="price" type="priceType" />
                <xs:element name="url" type="xs:string" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

<xs:complexType name="basePriceType">
        <xs:simpleContent>
            <xs:extension base="xs:double">
                <xs:attribute name="RMB" use="required"></xs:attribute>
            </xs:extension>
        </xs:simpleContent>
    </xs:complexType>

<xs:complexType name="priceType">
        <xs:simpleContent>
            <xs:restriction base="basePriceType">
                <xs:minExclusive value="0" />
                <xs:maxExclusive value="1000.00" />
            </xs:restriction>
        </xs:simpleContent>
    </xs:complexType>
</xs:schema>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

实例353  使用xs:restriction和xs:complexContent
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<books xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com restriction_complexContent_demo.xsd">
    <book>
        <name>《C#从入门到精通(第2版)》</name>
        <publisher>清华大学出版社</publisher>
        <company>明日科技</company>
        <author>王小科</author>
        <ISBN>9787302226628</ISBN>
        <price>69.80</price>
        <url>http://www.mingribook.com/bookinfo.php?id=227</url>

</book>
</books>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="books">
        <xs:complexType>
            <xs:all>
                <xs:element name="book" type="bookType" />
            </xs:all>
        </xs:complexType>
    </xs:element>

<xs:complexType name="baseBookType">
        <xs:sequence>
            <xs:element name="name" type="xs:string" />
            <xs:element name="publisher" type="xs:string" />
            <xs:element name="company" type="xs:string" />
            <xs:element name="author" type="xs:string" />
            <xs:element name="ISBN" type="xs:string" />
            <xs:element name="price" type="xs:double" />
            <xs:element name="url" type="xs:string" />
        </xs:sequence>
    </xs:complexType>

<xs:complexType name="bookType">
        <xs:complexContent>
            <xs:restriction base="baseBookType">
                <xs:sequence>
                    <xs:element name="name" type="xs:string" />
                    <xs:element name="publisher" type="xs:string" />
                    <xs:element name="company" type="xs:string" fixed="明日科技" />
                    <xs:element name="author" type="xs:string" />
                    <xs:element name="ISBN" type="xs:string" />
                    <xs:element name="price" type="xs:double" />
                    <xs:element name="url" type="xs:string" />
                </xs:sequence>
            </xs:restriction>
        </xs:complexContent>
    </xs:complexType>
</xs:schema>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

实例354  使用xs:attributeGroup和xs:attribute
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com attributeGroup_demo.xsd">

<name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author msn="wangxiaoke@mingrisoft.com" qq="200958602" tel="0431-84978981">王小科
    </author>
    <ISBN>9787302226628</ISBN>
    <price>2.0</price>
    <url>http://www.mingribook.com/bookinfo.php?id=227</url>
</book>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="name" type="xs:string" />
                <xs:element name="publisher" type="xs:string" />
                <xs:element name="company" type="xs:string" />
                <xs:element name="author">
                    <xs:complexType>
                        <xs:simpleContent>
                            <xs:extension base="xs:string">
                                <xs:attributeGroup ref="att"></xs:attributeGroup>
                            </xs:extension>
                        </xs:simpleContent>
                    </xs:complexType>
                </xs:element>
                <xs:element name="ISBN" type="xs:string" />
                <xs:element name="price" type="xs:double" />
                <xs:element name="url" type="xs:string" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

<xs:attributeGroup name="att">
        <xs:attribute name="tel" type="xs:string" use="required"></xs:attribute>
        <xs:attribute name="qq" type="xs:integer"></xs:attribute>
        <xs:attribute name="msn" type="xs:string"></xs:attribute>
    </xs:attributeGroup>

</xs:schema>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

11.4  使用XSD的普通类型
实例355  在XSD中对字符进行限制
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<bo:book xmlns:bo="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com string_demo.xsd">

<bo:name>《C#从入门到精通(第2版)》</bo:name>
    <bo:publisher>清华大学出版社</bo:publisher>
    <bo:company>bo:明日科技有限责任公司</bo:company>
    <bo:author>明日科技:王小科</bo:author>
</bo:book>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="name" type="xs:token" />
                <xs:element name="publisher" type="xs:NCName" />
                <xs:element name="company" type="xs:QName" />
                <xs:element name="author" type="xs:Name" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

实例356  在XSD中对数值进行限制
demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.mingrisoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com integer_demo.xsd">

<ISBN>9787302226628</ISBN>
    <pageNum>650</pageNum>
    <price>69.80</price>
</book>
demo.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.mingrisoft.com" xmlns="http://www.mingrisoft.com"
    elementFormDefault="qualified">

<xs:element name="book">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="ISBN" type="xs:positiveInteger" />
                <xs:element name="pageNum" type="xs:nonNegativeInteger" />
                <xs:element name="price" type="xs:double" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
demo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
<!--
#showError {
    color: #F00;
    font-size: 16px;
}
-->
</style></head>
<script type="text/javascript">
function validateXML(filename){
    var txt="";
    if (window.ActiveXObject){
        document.getElementById("showError").innerText ="";
        var xmlDoc = new ActiveXObject("MSXML2.DOMDocument.4.0");
          xmlDoc.async = false;
          xmlDoc.validateOnParse= true;
          xmlDoc.load(filename);

if(xmlDoc.parseError.errorCode!=0){
            txt="Error Code: " + xmlDoc.parseError.errorCode + "\n";
            txt=txt+"Error Reason: " + xmlDoc.parseError.reason ;
            txt=txt+"Error Line: " + xmlDoc.parseError.line;
        }else{
            txt="没有错误";
        }
        document.getElementById("showError").innerText = txt;
    }else{
              alert("此浏览器不支持验证!");
    }
    
}
</script>
<body>
<center>
<h2>通过XSD验证XML文件</h2>
<p>
<input id="xmlfile" type="text" />
<input type="button" name="submit" value="验 证" onClick="validateXML(document.getElementById('xmlfile').value);" />
</p>
</center>
<div id="showError"></div>
</body>
</html>

第12章  解析XML文件
12.1  使用SAX读取XML
实例357  从文件中读取XML
ParserFile.java
public void parseReadFile(String pathname) {
        SAXParser parser;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            parser = factory.newSAXParser();
            File file = new File(pathname);
            parser.parse(file, new DefaultHandler());
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

public static void main(String[] arg) {
        String pathname = "xmldemo/books.xml";
        new ParserFile().parseReadFile(pathname);
    }
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>
    
实例358  从数据流中读取XML
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>
ParserInputStream.java
    public void parseInputStream(InputStream inputStream) {
        SAXParser parser;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            parser = factory.newSAXParser();
            parser.parse(inputStream, new DefaultHandler());
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

public static void main(String[] arg) {

String pathname = "xmldemo/books.xml";
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(pathname));
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        new ParserInputStream().parseInputStream(inputStream);

try {
            inputStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

实例359  从数据源中读取XML
ParserInputSource.java
    public void parseInputSource(InputSource inputSource) {
        SAXParser parser;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            parser = factory.newSAXParser();
            parser.parse(inputSource, new DefaultHandler());
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

public static void main(String[] arg) {
        String pathname = "xmldemo/books.xml";
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(pathname));
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

InputSource inputSource = new InputSource(inputStream);
        new ParserInputSource().parseInputSource(inputSource);

try {
            inputStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>

12.2  使用SAX解析XML
实例360  解析XML元素名称
ElementNameSAXParsing.java
    private List<String> list = new ArrayList<String>();

/**
     * 重写父类方法,保存XML元素
     */
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        // TODO Auto-generated method stub
        list.add(localName);
    }

/**
     * 获取
     *
     * @return
     */
    public List<String> getList() {
        return this.list;
    }

/**
     * 通过文件读取XML
     *
     * @param pathname
     *            文件路径
     */
    public void parseReadFile(String pathname) {
        SAXParser parser;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            factory.setValidating(true);
            factory.setNamespaceAware(true);
            parser = factory.newSAXParser();
            File file = new File(pathname);
            parser.parse(file, this);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

public static void main(String[] arg) {

String pathname = "xmldemo/books.xml";
        ElementNameSAXParsing elementSAXParsing = new ElementNameSAXParsing();
        elementSAXParsing.parseReadFile(pathname);
        System.out.println("元素名称");
        System.out.println(elementSAXParsing.getList());
    }
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>
    
实例361  解析XML元素名称和内容
ElementValueSAXParsing.java
    private List<String> list = new ArrayList<String>();

private String value;

/**
     * 读取当前元素的内容,过滤回制表符、空格符、回车符、换行符
     */
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        //读取当前元素的内容,过滤回制表符、空格符、回车符、换行符
        value = String.valueOf(ch, start, length);
        value = value.replace("\t", "");
        value = value.replace(" ", "");
        value = value.replace("\n", "");
        value = value.replace("\r", "");
    }

/**
     * 读取元素结束,把元素名称和元素内容保存在list中
     */
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        //读取元素结束,把元素名称和元素内容保存在list中
        list.add(localName + ":" + value);
    }

public List<String> getList() {
        return this.list;
    }

/**
     * 通过文件读取XML
     *
     * @param pathname
     *            文件路径
     */
    public void parseReadFile(String pathname) {
        SAXParser parser;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            factory.setValidating(true);
            factory.setNamespaceAware(true);
            parser = factory.newSAXParser();
            File file = new File(pathname);
            parser.parse(file, this);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

public static void main(String[] arg) {

String pathname = "xmldemo/books.xml";
        ElementValueSAXParsing elementSAXParsing = new ElementValueSAXParsing();
        elementSAXParsing.parseReadFile(pathname);
        System.out.println("元素名称和元素内容");
        System.out.println(elementSAXParsing.getList());
    }
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>

实例362  解析XML元素属性和属性值
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>
AttributeSAXParsing.java
    List<String> attribute = new ArrayList<String>();

/**
     * 读取属性名称和属性值保存在List中
     */
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // 读取属性名称和属性值保存在List中
        for (int i = 0; i < attributes.getLength(); i++) {
            attribute.add(localName + " = " + attributes.getLocalName(i) + ":"
                    + attributes.getValue(i));
        }
    }

public List<String> getAttribute() {
        return this.attribute;
    }

/**
     * 通过文件读取XML
     *
     * @param pathname
     *            文件路径
     */
    public void parseReadFile(String pathname) {
        SAXParser parser;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            factory.setValidating(true);
            factory.setNamespaceAware(true);
            parser = factory.newSAXParser();
            File file = new File(pathname);
            parser.parse(file, this);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

public static void main(String[] arg) {

String pathname = "xmldemo/books.xml";
        AttributeSAXParsing elementSAXParsing = new AttributeSAXParsing();
        elementSAXParsing.parseReadFile(pathname);
        System.out.println("属性名称和属性值");
        System.out.println(elementSAXParsing.getAttribute());
    }
    
实例363  使用VO解析XML元素
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>
BookElement.java
    private String name;
    private String publisher;
    private String company;
    private String author;
    private String isbn;
    private Double price;
    private URL url;

public String getName() {
        return this.name;
    }

public void setName(String name) {
        this.name = name;
    }

public String getPublisher() {
        return this.publisher;
    }

public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

public String getCompany() {
        return this.company;
    }

public void setCompany(String company) {
        this.company = company;
    }

public String getAuthor() {
        return this.author;
    }

public void setAuthor(String author) {
        this.author = author;
    }

public String getIsbn() {
        return this.isbn;
    }

public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

public Double getPrice() {
        return this.price;
    }

public void setPrice(Double price) {
        this.price = price;
    }

public URL getUrl() {
        return this.url;
    }

public void setUrl(URL url) {
        this.url = url;
    }

@Override
    public String toString() {
        // TODO Auto-generated method stub
        StringBuffer buffer = new StringBuffer();
        buffer.append("name=" + this.name + "\n");
        buffer.append("publisher=" + this.publisher + "\n");
        buffer.append("company=" + this.company + "\n");
        buffer.append("author=" + this.author + "\n");
        buffer.append("isbn=" + this.isbn + "\n");
        buffer.append("price=" + this.price + "\n");
        buffer.append("url=" + this.url + "\n");

return buffer.toString();
    }
BookElementSAXParsing.java
    private List<BookElement> bookList;

private BookElement bookElement;

private String elementValue;

@Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
        bookList = new ArrayList<BookElement>();
    }

@Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // TODO Auto-generated method stub

// 每次读取book元素的时候重新初始化bookElement
        if (bookElement == null || "book".equals(localName)) {
            bookElement = new BookElement();
        }
    }

/**
     * 元素结束时,把元素内容置到book中
     */
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        // TODO Auto-generated method stub

if ("name".equals(localName)) {
            bookElement.setName(elementValue);
        } else if ("publisher".equals(localName)) {
            bookElement.setPublisher(elementValue);
        } else if ("company".equals(localName)) {
            bookElement.setCompany(elementValue);
        } else if ("author".equals(localName)) {
            bookElement.setAuthor(elementValue);
        } else if ("ISBN".equals(localName)) {
            bookElement.setIsbn(elementValue);
        } else if ("price".equals(localName)) {
            bookElement.setPrice(Double.valueOf(elementValue));
        } else if ("url".equals(localName)) {
            try {
                bookElement.setUrl(new URL(elementValue));
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else if ("book".equals(localName)) {
            bookList.add(bookElement);
        }

实例364  使用VO解析XML元素和属性
Book.java
    private String name;
    private String publisher;
    private String company;
    private String author;
    private String isbn;
    private BookPrice price;
    private URL url;

public String getName() {
        return this.name;
    }

public void setName(String name) {
        this.name = name;
    }

public String getPublisher() {
        return this.publisher;
    }

public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

public String getCompany() {
        return this.company;
    }

public void setCompany(String company) {
        this.company = company;
    }

public String getAuthor() {
        return this.author;
    }

public void setAuthor(String author) {
        this.author = author;
    }

public String getIsbn() {
        return this.isbn;
    }

public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

public BookPrice getPrice() {
        return this.price;
    }

public void setPrice(BookPrice price) {
        this.price = price;
    }

public URL getUrl() {
        return this.url;
    }

public void setUrl(URL url) {
        this.url = url;
    }

@Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("name=" + this.name + "\n");
        buffer.append("publisher=" + this.publisher + "\n");
        buffer.append("company=" + this.company + "\n");
        buffer.append("author=" + this.author + "\n");
        buffer.append("isbn=" + this.isbn + "\n");
        buffer.append("price=" + this.price + "\n");
        buffer.append("url=" + this.url + "\n");

return buffer.toString();
    }
BookPrice.java
    // 属性名称和属性值列表
    private Map<String, String> attributeMap;
    // 价格值
    private Double value;

public Map<String, String> getAttributeMap() {
        return this.attributeMap;
    }

public void setAttributeMap(Map<String, String> attributeMap) {
        this.attributeMap = attributeMap;
    }

public Double getValue() {
        return this.value;
    }

public void setValue(Double value) {
        this.value = value;
    }

@Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("[atrributes=" + this.attributeMap + "\n");
        buffer.append("vlaue=" + this.value + "\n]");
        return buffer.toString();
    }
BookSAXParsing.java
    private List<Book> bookList;

private Book book;

private BookPrice bookPrice;

private String elementValue;

@Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
        bookList = new ArrayList<Book>();
    }

/**
     * 读取元素、属性,把元素、属性名称保存在list中
     */
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // TODO Auto-generated method stub

if (book == null || "book".equals(localName)) {
            book = new Book();
        }

if (bookPrice == null || "price".equals(localName)) {
            bookPrice = new BookPrice();
            // 读取属性名称和值
            Map<String, String> attributeMap = new HashMap<String, String>();
            for (int i = 0; i < attributes.getLength(); i++) {
                attributeMap.put(attributes.getLocalName(i),
                        attributes.getValue(i));
            }
            if (!attributeMap.isEmpty()) {
                bookPrice.setAttributeMap(attributeMap);
            }

}
    }

@Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        // TODO Auto-generated method stub

if ("name".equals(localName)) {
            book.setName(elementValue);
        } else if ("publisher".equals(localName)) {
            book.setPublisher(elementValue);
        } else if ("company".equals(localName)) {
            book.setCompany(elementValue);
        } else if ("author".equals(localName)) {
            book.setAuthor(elementValue);
        } else if ("ISBN".equals(localName)) {
            book.setIsbn(elementValue);
        } else if ("price".equals(localName)) {
            bookPrice.setValue(Double.valueOf(elementValue));
            book.setPrice(bookPrice);
        } else if ("url".equals(localName)) {
            try {
                book.setUrl(new URL(elementValue));
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else if ("book".equals(localName)) {
            bookList.add(book);
        }
    }

/**
     * 解析元素内容
     */
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        // TODO Auto-generated method stub
        elementValue = elementValue.valueOf(ch, start, length);
        elementValue = elementValue.replace("\t", "");
        elementValue = elementValue.replace(" ", "");
        elementValue = elementValue.replace("\n", "");
        elementValue = elementValue.replace("\r", "");
    }

public List<Book> getBookList() {
        return this.bookList;
    }

/**
     * 通过文件读取XML
     *
     * @param pathname
     *            文件路径
     */
    public void parseReadFile(String pathname) {
        SAXParser parser;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            factory.setValidating(true);
            factory.setNamespaceAware(true);
            parser = factory.newSAXParser();
            File file = new File(pathname);
            parser.parse(file, this);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

public static void main(String[] arg) {

String pathname = "xmldemo/books.xml";
        BookSAXParsing elementSAXParsing = new BookSAXParsing();
        elementSAXParsing.parseReadFile(pathname);
        System.out.println("自定义JAVA类封装元素名称和内容");
        System.out.println(elementSAXParsing.getBookList());
    }
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>
    
实例365  使用SAX验证DTD
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book SYSTEM "books.dtd">
<book>
    <name>《C#从入门到精通(第2版)》</name>
    <publisher>清华大学出版社</publisher>
    <company>明日科技</company>
    <author>王小科</author>
    <ISBN>9787302226628</ISBN>
    <price>69.80</price>
    <url><![CDATA[http://www.mingribook.com/bookinfo.php?id=227&sid=4]]></url>
</book>
books.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT book (name,publisher,company,author,ISBN,price,url)>
<!ELEMENT name      (#PCDATA)>
<!ELEMENT publisher    (#PCDATA)>
<!ELEMENT company     (#PCDATA)>
<!ELEMENT author    (#PCDATA)>
<!ELEMENT ISBN    (#PCDATA)>
<!ELEMENT price    (#PCDATA)>
<!ELEMENT url    (#PCDATA)>
<!ATTLIST price unit CDATA "RMB" >
ErrorSAXParsing.java
    public void warning(SAXParseException exception) throws SAXException {
        // TODO Auto-generated method stub
        System.out.println("warning");
        System.out.println("错误位置:" + exception.getLineNumber() + "行"
                + exception.getColumnNumber() + "列");
        System.out.println("错误信息:" + exception.getMessage());
    }

public void error(SAXParseException exception) throws SAXException {
        // TODO Auto-generated method stub
        System.out.println("error");
        System.out.println("错误位置:" + exception.getLineNumber() + "行"
                + exception.getColumnNumber() + "列");
        System.out.println("错误信息:" + exception.getMessage());
    }

public void fatalError(SAXParseException exception) throws SAXException {
        // TODO Auto-generated method stub
        System.out.println("fdatalError");
        System.out.println("错误位置:" + exception.getLineNumber() + "行"
                + exception.getColumnNumber() + "列");
        System.out.println("错误信息:" + exception.getMessage());

}

/**
     * 通过文件读取XML
     *
     * @param pathname
     *            文件路径
     */
    public void parseReadFile(String pathname) {
        SAXParser parser;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            factory.setValidating(true);
            factory.setNamespaceAware(true);
            parser = factory.newSAXParser();
            File file = new File(pathname);
            parser.parse(file, this);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static void main(String[] arg) {

String pathname = "xmldemo/books.xml";
        ErrorSAXParsing elementSAXParsing = new ErrorSAXParsing();
        elementSAXParsing.parseReadFile(pathname);
    }

12.3  使用DOM读取XML
实例366  从文件中读取XML
ParserFile.java
    public void parseReadFile(String path) throws ParserConfigurationException,
            SAXException, IOException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dombuilder = documentBuilderFactory
                .newDocumentBuilder();
        File file = new File(path);
        dombuilder.parse(file);

}

public static void main(String[] arg) {
        ParserFile parserFile = new ParserFile();
        String path = "xmldemo/books.xml";
        try {

parserFile.parseReadFile(path);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>
    
实例367  从数据流中读取XML
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>
ParserInputStream.java
    public void parseInputStream(String path)
            throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dombuilder = documentBuilderFactory
                .newDocumentBuilder();
        InputStream is = new FileInputStream(path);
        dombuilder.parse(is);
        is.close();

}

public static void main(String[] arg) {
        ParserInputStream parserFile = new ParserInputStream();
        String path = "xmldemo/books.xml";
        try {

parserFile.parseInputStream(path);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

实例368  从数据源中读取XML
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>
ParserInputSource.java
    public void parseInputSource(InputSource is)
            throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dombuilder = documentBuilderFactory
                .newDocumentBuilder();
        dombuilder.parse(is);

}

public static void main(String[] arg) {
        ParserInputSource parserFile = new ParserInputSource();
        String systemId = "xmldemo/books.xml";
        InputSource is = new InputSource(systemId);
        try {
            parserFile.parseInputSource(is);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

12.4  使用DOM解析XML
实例369  解析XML元素名称
ElementNameDOMParserFile.java
    private List<String> elementList = new ArrayList<String>();

/**
     * 读取XML文件
     *
     * @param path
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    public Document parseReadFile(String path)
            throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dombuilder = documentBuilderFactory
                .newDocumentBuilder();
        File file = new File(path);
        return dombuilder.parse(file);
    }

/**
     * 获取{@link Node}的name
     *
     * @param parentNode
     * @return
     */
    public List<String> getElementName(Node parentNode) {
        if (parentNode.hasChildNodes()) {
            NodeList nodeList = parentNode.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.hasChildNodes()) {
                    getElementName(node);
                    elementList.add((node.getNodeName()));
                }
                    
            }
        }
        return elementList;
    }

public static void main(String[] arg) {
        ElementNameDOMParserFile parserFile = new ElementNameDOMParserFile();
        String path = "xmldemo/books.xml";
        try {

Document document = parserFile.parseReadFile(path);
            List<String> list = parserFile.getElementName(document);
            System.out.println("XML元素名称");
            System.out.println(list);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>
    
实例370  解析XML元素名称和内容
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>
ElementValueDOMParserFile.java
    private List<String> elementList = new ArrayList<String>();

/**
     * 读取XML文件
     *
     * @param path
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    public Document parseReadFile(String path)
            throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dombuilder = documentBuilderFactory
                .newDocumentBuilder();
        File file = new File(path);
        return dombuilder.parse(file);
    }

/**
     * 获取{@link Node}的name和textcontent
     *
     * @param parentNode
     */
    public void getElementName(Node parentNode) {
        if (parentNode.hasChildNodes()) {
            NodeList nodeList = parentNode.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.hasChildNodes()) {
                    getElementName(node);
                    elementList.add(node.getNodeName() + "-"
                            + node.getTextContent());
                }
            }
        }
    }

public List<String> getElementList() {
        return this.elementList;
    }

public static void main(String[] arg) {
        ElementValueDOMParserFile parserFile = new ElementValueDOMParserFile();
        String path = "xmldemo/books.xml";
        try {

Document document = parserFile.parseReadFile(path);
            parserFile.getElementName(document);
            List<String> list = parserFile.getElementList();
            System.out.println("XML元素名称和内容");
            System.out.println(list);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

实例371  解析XML元素属性和属性值
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>
AttriburteDOMParserFile.java
    private List<String> elementList = new ArrayList<String>();

/**
     * 读取XML文件
     *
     * @param path
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    public Document parseReadFile(String path)
            throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dombuilder = documentBuilderFactory
                .newDocumentBuilder();
        File file = new File(path);
        return dombuilder.parse(file);
    }

/**
     * 获取{@link Node}的name,和value
     *
     * @param parentNode
     */
    public void getElementName(Node parentNode) {
        if (parentNode.hasChildNodes()) {
            NodeList nodeList = parentNode.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.hasChildNodes()) {
                    getElementName(node);
                    NamedNodeMap namedNodeMap = node.getAttributes();
                    for (int j = 0; j < namedNodeMap.getLength(); j++) {
                        Node node2 = namedNodeMap.item(j);
                        elementList.add(node.getNodeName() + " = "
                                + node2.getNodeName() + " > "
                                + node2.getNodeValue());
                    }
                }
            }
        }
    }

public List<String> getElementList() {
        return this.elementList;
    }

public static void main(String[] arg) {
        AttriburteDOMParserFile parserFile = new AttriburteDOMParserFile();
        String path = "xmldemo/books.xml";
        try {

Document document = parserFile.parseReadFile(path);
            parserFile.getElementName(document);
            List<String> list = parserFile.getElementList();
            System.out.println("属性名称和属性值");
            System.out.println(list);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

实例372  使用VO解析XML元素
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>
BookElement.java
    private String name;
    private String publisher;
    private String company;
    private String author;
    private String isbn;
    private Double price;
    private URL url;

public String getName() {
        return this.name;
    }

public void setName(String name) {
        this.name = name;
    }

public String getPublisher() {
        return this.publisher;
    }

public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

public String getCompany() {
        return this.company;
    }

public void setCompany(String company) {
        this.company = company;
    }

public String getAuthor() {
        return this.author;
    }

public void setAuthor(String author) {
        this.author = author;
    }

public String getIsbn() {
        return this.isbn;
    }

public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

public Double getPrice() {
        return this.price;
    }

public void setPrice(Double price) {
        this.price = price;
    }

public URL getUrl() {
        return this.url;
    }

public void setUrl(URL url) {
        this.url = url;
    }

@Override
    public String toString() {
        // TODO Auto-generated method stub
        StringBuffer buffer = new StringBuffer();
        buffer.append("name=" + this.name + "\n");
        buffer.append("publisher=" + this.publisher + "\n");
        buffer.append("company=" + this.company + "\n");
        buffer.append("author=" + this.author + "\n");
        buffer.append("isbn=" + this.isbn + "\n");
        buffer.append("price=" + this.price + "\n");
        buffer.append("url=" + this.url + "\n");

return buffer.toString();
    }
BookElementDOMParsing.java
    private List<BookElement> bookList = new ArrayList<BookElement>();

private BookElement bookElement;

/**
     * 读取XML文件
     *
     * @param path
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    public Document parseReadFile(String path) {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dombuilder = null;
        try {
            dombuilder = documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        File file = new File(path);
        try {
            return dombuilder.parse(file);
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

/**
     * 获取{@link Node}的name和textcontent
     *
     * @param document
     */
    public List<BookElement> getBook(Element element) {
        NodeList list = element.getElementsByTagName("book:book");

for (int i = 0; i < list.getLength(); i++) {
            bookElement = new BookElement();
            NodeList name = element.getElementsByTagName("book:name");
            NodeList publisher = element.getElementsByTagName("book:publisher");
            NodeList company = element.getElementsByTagName("book:company");
            NodeList author = element.getElementsByTagName("book:author");
            NodeList ISBN = element.getElementsByTagName("book:ISBN");
            NodeList price = element.getElementsByTagName("book:price");
            NodeList url = element.getElementsByTagName("book:url");
            bookElement.setName(name.item(i).getTextContent());
            bookElement.setPublisher(publisher.item(i).getTextContent());
            bookElement.setCompany(company.item(i).getTextContent());
            bookElement.setAuthor(author.item(i).getTextContent());
            bookElement.setIsbn(ISBN.item(i).getTextContent());
            bookElement.setPrice(new Double(price.item(i).getTextContent()));
            try {
                bookElement.setUrl(new URL(url.item(i).getTextContent()));
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (DOMException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            bookList.add(bookElement);
        }
        return bookList;
    }

public static void main(String[] arg) {

String pathname = "xmldemo/books.xml";
        BookElementDOMParsing elementSAXParsing = new BookElementDOMParsing();
        Document document = null;
        document = elementSAXParsing.parseReadFile(pathname);
        List<BookElement> bookElements = elementSAXParsing.getBook(document
                .getDocumentElement());
        System.out.println("自定义JAVA类封装元素名称和内容");
        System.out.println(bookElements);
    }

实例373  使用VO解析XML元素和属性
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.mingrisoft.com"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mingrisoft.com books.xsd">
    <book:book>
        <book:name>《C#从入门到精通(第2版)》</book:name>
        <book:publisher>清华大学出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>王小科</book:author>
        <book:ISBN>9787302226628</book:ISBN>
        <book:price unit="yuan" unitType="RMB">69.80</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url>
    </book:book>
    <book:book>
        <book:name>《JavaScript开发技术大全》</book:name>
        <book:publisher>人民邮电出版社</book:publisher>
        <book:company>明日科技</book:company>
        <book:author>梁冰</book:author>
        <book:ISBN>9787115179708</book:ISBN>
        <book:price unit="yuan" unitType="RMB">65.00</book:price>
        <book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url>
    </book:book>
</book:books>
Book.java
    private String name;
    private String publisher;
    private String company;
    private String author;
    private String isbn;
    private BookPrice price;
    private URL url;

public String getName() {
        return this.name;
    }

public void setName(String name) {
        this.name = name;
    }

public String getPublisher() {
        return this.publisher;
    }

public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

public String getCompany() {
        return this.company;
    }

public void setCompany(String company) {
        this.company = company;
    }

public String getAuthor() {
        return this.author;
    }

public void setAuthor(String author) {
        this.author = author;
    }

public String getIsbn() {
        return this.isbn;
    }

public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

public BookPrice getPrice() {
        return this.price;
    }

public void setPrice(BookPrice price) {
        this.price = price;
    }

public URL getUrl() {
        return this.url;
    }

public void setUrl(URL url) {
        this.url = url;
    }

@Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("name=" + this.name + "\n");
        buffer.append("publisher=" + this.publisher + "\n");
        buffer.append("company=" + this.company + "\n");
        buffer.append("author=" + this.author + "\n");
        buffer.append("isbn=" + this.isbn + "\n");
        buffer.append("price=" + this.price + "\n");
        buffer.append("url=" + this.url + "\n");

return buffer.toString();
    }
BookPrice.java
    private Map<String, String> attributeMap;
    // 价格值
    private Double value;

public Map<String, String> getAttributeMap() {
        return this.attributeMap;
    }

public void setAttributeMap(Map<String, String> attributeMap) {
        this.attributeMap = attributeMap;
    }

public Double getValue() {
        return this.value;
    }

public void setValue(Double value) {
        this.value = value;
    }

@Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("[atrributes=" + this.attributeMap + "\n");
        buffer.append("vlaue=" + this.value + "\n]");
        return buffer.toString();
    }
BookDOMParsing.java
    private List<Book> bookList = new ArrayList<Book>();

private Book book;

/**
     * 读取XML文件
     *
     * @param path
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    public Document parseReadFile(String path) {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dombuilder = null;
        try {
            dombuilder = documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        File file = new File(path);
        try {
            return dombuilder.parse(file);
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

/**
     * 获取{@link Node}的name和textcontent
     *
     * @param document
     */
    public List<Book> getBook(Element element) {
        NodeList list = element.getElementsByTagName("book:book");

for (int i = 0; i < list.getLength(); i++) {
            book = new Book();
            NodeList name = element.getElementsByTagName("book:name");
            NodeList publisher = element.getElementsByTagName("book:publisher");
            NodeList company = element.getElementsByTagName("book:company");
            NodeList author = element.getElementsByTagName("book:author");
            NodeList ISBN = element.getElementsByTagName("book:ISBN");
            NodeList price = element.getElementsByTagName("book:price");
            NodeList url = element.getElementsByTagName("book:url");
            book.setName(name.item(i).getTextContent());
            book.setPublisher(publisher.item(i).getTextContent());
            book.setCompany(company.item(i).getTextContent());
            book.setAuthor(author.item(i).getTextContent());
            book.setIsbn(ISBN.item(i).getTextContent());

// 获取价格
            BookPrice bookPrice = new BookPrice();
            Map<String, String> attributeMap = new HashMap<String, String>();
            NamedNodeMap namedNodeMap = price.item(i).getAttributes();
            for (int j = 0; j < namedNodeMap.getLength(); j++) {
                // 获取价格属性
                Node node = namedNodeMap.item(j);
                attributeMap.put(node.getNodeName(), node.getNodeValue());
            }
            bookPrice.setAttributeMap(attributeMap);
            bookPrice.setValue(new Double(price.item(i).getTextContent()));
            book.setPrice(bookPrice);

// 获取URL
            try {
                book.setUrl(new URL(url.item(i).getTextContent()));
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (DOMException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            bookList.add(book);
        }
        return bookList;
    }

public static void main(String[] arg) {

String pathname = "xmldemo/books.xml";
        BookDOMParsing elementSAXParsing = new BookDOMParsing();
        Document document = null;
        document = elementSAXParsing.parseReadFile(pathname);
        List<Book> bookElements = elementSAXParsing.getBook(document
                .getDocumentElement());
        System.out.println("自定义JAVA类封装元素名称和内容");
        System.out.println(bookElements);

}

12.5  使用DOM操作XML
实例374  创建简单的XML文件
demo.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><book:book xmlns:book="http://www.mingrisoft.com"/>
BulidFile.java
    public void writeFile(Node node, String url) {
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        DOMSource domSource = new DOMSource(node);
        StreamResult streamResult = new StreamResult(new File(url));
        try {
            Transformer transformer = transformerFactory.newTransformer();
            transformer.transform(domSource, streamResult);
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

/**
     * 建立XML文件
     *
     * @return
     */
    public Document bulid() {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dombuilder = null;
        try {
            dombuilder = documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Document document = dombuilder.newDocument();
        Element book = document.createElement("book:book");
        book.setAttribute("xmlns:book", "http://www.mingrisoft.com");
        document.appendChild(book);

return document;
    }

public static void main(String[] arg) {

String pathname = "xmldemo/BulidFile.xml";
        BulidFile bulid = new BulidFile();
        bulid.writeFile(bulid.bulid(), pathname);
        
    }

实例375  创建基本的XML文件
ElementDOMBulid.java
    public void writeFile(Node node, String url) {
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        DOMSource domSource = new DOMSource(node);
        StreamResult streamResult = new StreamResult(new File(url));
        try {
            Transformer transformer = transformerFactory.newTransformer();
            transformer.transform(domSource, streamResult);
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

public Document bulid() {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dombuilder = null;
        try {
            dombuilder = documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Document document = dombuilder.newDocument();
        Element books = document.createElement("book:books");
        books.setAttribute("xmlns:book", "http://www.mingrisoft.com");

Element book = document.createElement("book:book");
        Element name = document.createElement("book:name");
        Element publisher = document.createElement("book:publisher");
        Element company = document.createElement("book:company");
        Element author = document.createElement("book:author");
        Element isbn = document.createElement("book:ISBN");
        Element price = document.createElement("book:price");
        Element url = document.createElement("book:url");

name.setTextContent("《C#从入门到精通(第2版)》");
        publisher.setTextContent("清华大学出版社");
        company.setTextContent("明日科技");
        author.setTextContent("王小科");
        isbn.setTextContent("9787302226628");
        price.setTextContent("69.80");
        url.setTextContent("http://www.mingribook.com/bookinfo.php?id=227");

book.appendChild(name);
        book.appendChild(publisher);
        book.appendChild(company);
        book.appendChild(author);
        book.appendChild(isbn);
        book.appendChild(price);
        book.appendChild(url);
        books.appendChild(book);
        document.appendChild(books);

return document;
    }

public static void main(String[] arg) {

String pathname = "xmldemo/ElementDOMBulid.xml";
        ElementDOMBulid bulid = new ElementDOMBulid();
        bulid.writeFile(bulid.bulid(), pathname);

}
ElementDOMBulid.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><book:books xmlns:book="http://www.mingrisoft.com"><book:book><book:name>《C#从入门到精通(第2版)》</book:name><book:publisher>清华大学出版社</book:publisher><book:company>明日科技</book:company><book:author>王小科</book:author><book:ISBN>9787302226628</book:ISBN><book:price>69.80</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url></book:book></book:books>

实例376  使用VO创建XML文件
BookDOMBulid.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><book:books xmlns:book="http://www.mingrisoft.com"><book:book><book:name>《C#从入门到精通(第2版)》</book:name><book:publisher>清华大学出版社</book:publisher><book:company>明日科技</book:company><book:author>王小科</book:author><book:ISBN>9787302226628</book:ISBN><book:price>69.8</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url></book:book><book:book><book:name>《JavaScript开发技术大全》</book:name><book:publisher>人民邮电出版社</book:publisher><book:company>明日科技</book:company><book:author>梁冰</book:author><book:ISBN>9787115179708</book:ISBN><book:price>65.0</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url></book:book></book:books>
BookDOMBulid.java
    protected List<Book> initData() {
        List<Book> bookList = new ArrayList<Book>();
        Book book;
        BookPrice bookPrice;
        Map<String, String> attributeMap;

// 第一本书
        book = new Book();
        bookPrice = new BookPrice();
        book.setName("《C#从入门到精通(第2版)》");
        book.setPublisher("清华大学出版社");
        book.setCompany("明日科技");
        book.setAuthor("王小科");
        book.setIsbn("9787302226628");

attributeMap = new HashMap<String, String>();
        attributeMap.put("unit", "yuan");
        attributeMap.put("unitType", "RMB");
        bookPrice.setAttributeMap(attributeMap);
        bookPrice.setValue(Double.parseDouble("69.80"));
        book.setPrice(bookPrice);
        try {
            book.setUrl(new URL("http://www.mingribook.com/bookinfo.php?id=227"));
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        bookList.add(book);

// 第二本书
        book = new Book();
        bookPrice = new BookPrice();
        book.setName("《JavaScript开发技术大全》");
        book.setPublisher("人民邮电出版社");
        book.setCompany("明日科技");
        book.setAuthor("梁冰");
        book.setIsbn("9787115179708");

attributeMap = new HashMap<String, String>();
        attributeMap.put("unit", "yuan");
        attributeMap.put("unitType", "RMB");
        bookPrice.setAttributeMap(attributeMap);
        bookPrice.setValue(Double.parseDouble("65.00"));
        book.setPrice(bookPrice);
        try {
            book.setUrl(new URL("http://www.mingribook.com/bookinfo.php?id=138"));
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        bookList.add(book);

// 第三本书
        // ......

return bookList;

}

/**
     * 创建XML文件
     *
     * @param node
     *            DOM节点
     * @param url
     *            XML文件路径
     */
    public void writeFile(Node node, String url) {
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        DOMSource domSource = new DOMSource(node);
        StreamResult streamResult = new StreamResult(new File(url));
        try {
            Transformer transformer = transformerFactory.newTransformer();
            transformer.transform(domSource, streamResult);
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

/**
     * 创建XML
     *
     * @return
     */
    public Document bulid() {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dombuilder = null;
        Document document = null;
        try {
            dombuilder = documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        List<Book> bookList =initData();
        System.out.println(bookList);
        if (bookList != null) {

document = dombuilder.newDocument();
            Element books = document.createElement("book:books");
            books.setAttribute("xmlns:book", "http://www.mingrisoft.com");
            for (Iterator iterator = bookList.iterator(); iterator.hasNext();) {
                Book bookEntity = (Book) iterator.next();

Element book = document.createElement("book:book");
                Element name = document.createElement("book:name");
                Element publisher = document.createElement("book:publisher");
                Element company = document.createElement("book:company");
                Element author = document.createElement("book:author");
                Element isbn = document.createElement("book:ISBN");
                Element price = document.createElement("book:price");
                Element url = document.createElement("book:url");

name.setTextContent(bookEntity.getName());
                publisher.setTextContent(bookEntity.getPublisher());
                company.setTextContent(bookEntity.getCompany());
                author.setTextContent(bookEntity.getAuthor());
                isbn.setTextContent(bookEntity.getIsbn());
                price.setTextContent(bookEntity.getPrice().getValue()
                        .toString());
                url.setTextContent(bookEntity.getUrl().toString());

book.appendChild(name);
                book.appendChild(publisher);
                book.appendChild(company);
                book.appendChild(author);
                book.appendChild(isbn);
                book.appendChild(price);
                book.appendChild(url);

books.appendChild(book);
            }
            document.appendChild(books);
        }

return document;
    }

public static void main(String[] arg) {

String pathname = "xmldemo/BookDOMBulid.xml";
        BookDOMBulid bulid = new BookDOMBulid();
        bulid.writeFile(bulid.bulid(), pathname);

}
Book.java
    private String name;
    private String publisher;
    private String company;
    private String author;
    private String isbn;
    private BookPrice price;
    private URL url;

public String getName() {
        return this.name;
    }

public void setName(String name) {
        this.name = name;
    }

public String getPublisher() {
        return this.publisher;
    }

public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

public String getCompany() {
        return this.company;
    }

public void setCompany(String company) {
        this.company = company;
    }

public String getAuthor() {
        return this.author;
    }

public void setAuthor(String author) {
        this.author = author;
    }

public String getIsbn() {
        return this.isbn;
    }

public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

public BookPrice getPrice() {
        return this.price;
    }

public void setPrice(BookPrice price) {
        this.price = price;
    }

public URL getUrl() {
        return this.url;
    }

public void setUrl(URL url) {
        this.url = url;
    }

@Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("name=" + this.name + "\n");
        buffer.append("publisher=" + this.publisher + "\n");
        buffer.append("company=" + this.company + "\n");
        buffer.append("author=" + this.author + "\n");
        buffer.append("isbn=" + this.isbn + "\n");
        buffer.append("price=" + this.price + "\n");
        buffer.append("url=" + this.url + "\n");

return buffer.toString();
    }
BookPrice.java
    private Map<String, String> attributeMap;
    // 价格值
    private Double value;

public Map<String, String> getAttributeMap() {
        return this.attributeMap;
    }

public void setAttributeMap(Map<String, String> attributeMap) {
        this.attributeMap = attributeMap;
    }

public Double getValue() {
        return this.value;
    }

public void setValue(Double value) {
        this.value = value;
    }

@Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("[atrributes=" + this.attributeMap + "\n");
        buffer.append("vlaue=" + this.value + "\n]");
        return buffer.toString();
    }

实例377  使用DOM添加XML元素
BookDOMAdd.java
    private Document document = null;

private String path = null;

public BookDOMAdd(String path) {
        // TODO Auto-generated constructor stub
        this.path = path;
    }

/**
     * 读取XML文件
     *
     * @param path
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    private void parseReadFile() {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dombuilder = null;
        try {
            dombuilder = documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        File file = new File(path);
        try {
            document = dombuilder.parse(file);
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

/**
     * 添加book子节点
     */
    public void addBook() {
        parseReadFile();

Element book = document.createElement("book:book");
        Element name = document.createElement("book:name");
        Element publisher = document.createElement("book:publisher");
        Element company = document.createElement("book:company");
        Element author = document.createElement("book:author");
        Element isbn = document.createElement("book:ISBN");
        Element price = document.createElement("book:price");
        Element url = document.createElement("book:url");

name.setTextContent("《Java全能速查宝典》");
        publisher.setTextContent("人民邮电出版社");
        company.setTextContent("明日科技");
        author.setTextContent("梁冰");
        isbn.setTextContent("9787115214874");
        price.setTextContent("59.00");
        price.setAttribute("unit", "yuan");
        price.setAttribute("unitType", "RMB");
        url.setTextContent("http://www.mingribook.com/bookinfo.php?id=191");

book.appendChild(name);
        book.appendChild(publisher);
        book.appendChild(company);
        book.appendChild(author);
        book.appendChild(isbn);
        book.appendChild(price);
        book.appendChild(url);

document.getDocumentElement().appendChild(book);
    }

/**
     * 创建XML文件
     *
     * @param node
     *            DOM节点
     * @param url
     *            XML文件路径
     */
    public void writeFile(String out) {
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        DOMSource domSource = new DOMSource(document);
        StreamResult streamResult = new StreamResult(new File(out));
        try {
            Transformer transformer = transformerFactory.newTransformer();
            transformer.transform(domSource, streamResult);
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

public static void main(String[] arg) {
        String in = "xmldemo/BookDOMBulid.xml";
        String out = "xmldemo/BookDOMAdd.xml";
        BookDOMAdd bulid = new BookDOMAdd(in);
        bulid.addBook();
        bulid.writeFile(out);
    }
BookDOMAdd.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><book:books xmlns:book="http://www.mingrisoft.com"><book:book><book:name>《C#从入门到精通(第2版)》</book:name><book:publisher>清华大学出版社</book:publisher><book:company>明日科技</book:company><book:author>王小科</book:author><book:ISBN>9787302226628</book:ISBN><book:price>69.8</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url></book:book><book:book><book:name>《JavaScript开发技术大全》</book:name><book:publisher>人民邮电出版社</book:publisher><book:company>明日科技</book:company><book:author>梁冰</book:author><book:ISBN>9787115179708</book:ISBN><book:price>65.0</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url></book:book><book:book><book:name>《Java全能速查宝典》</book:name><book:publisher>人民邮电出版社</book:publisher><book:company>明日科技</book:company><book:author>梁冰</book:author><book:ISBN>9787115214874</book:ISBN><book:price unit="yuan" unitType="RMB">59.00</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=191</book:url></book:book></book:books>
BookDOMBulid.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><book:books xmlns:book="http://www.mingrisoft.com"><book:book><book:name>《C#从入门到精通(第2版)》</book:name><book:publisher>清华大学出版社</book:publisher><book:company>明日科技</book:company><book:author>王小科</book:author><book:ISBN>9787302226628</book:ISBN><book:price>69.8</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url></book:book><book:book><book:name>《JavaScript开发技术大全》</book:name><book:publisher>人民邮电出版社</book:publisher><book:company>明日科技</book:company><book:author>梁冰</book:author><book:ISBN>9787115179708</book:ISBN><book:price>65.0</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url></book:book></book:books>

实例378  使用DOM修改XML元素
BookDOMUpdate.java
    private Document document = null;

private String path = null;

public BookDOMUpdate(String path) {
        // TODO Auto-generated constructor stub
        this.path = path;
    }

/**
     * 读取XML文件
     *
     * @param path
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    private void parseReadFile() {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dombuilder = null;
        try {
            dombuilder = documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        File file = new File(path);
        try {
            document = dombuilder.parse(file);
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

/**
     * 根据book子节点指定的条件更新元素的内容
     *
     * @param nodeName
     *            指定条件元素名称
     * @param text
     *            指定条件元素内容
     * @param replNodeName
     *            指定更新的节点
     * @param repltext
     *            设置更新的内容
     */
    public void updateBook(String nodeName, String text, String replNodeName,
            String repltext) {
        parseReadFile();

NodeList list = document.getElementsByTagName("book:book");
        for (int i = 0; i < list.getLength(); i++) {
            boolean flag = false;
            Node bookNode = list.item(i);
            NodeList list1 = bookNode.getChildNodes();
            // 查询出需要修改的book节点
            for (int j = 0; j < list1.getLength(); j++) {
                Node node1 = list1.item(j);
                if (node1.getNodeName().equals(nodeName)
                        && node1.getTextContent().equals(text)) {
                    flag = true;
                }
            }
            // 查询到需要的book节点,设置指定的元素内容
            if (flag) {
                for (int j = 0; j < list1.getLength(); j++) {
                    Node node1 = list1.item(j);
                    // 查询出需要修改的节点
                    if (node1.getNodeName().equals(replNodeName)) {
                        node1.setTextContent(repltext);
                    }
                }
                flag = false;
            }

}

}

/**
     * 创建XML文件
     *
     * @param node
     *            DOM节点
     * @param url
     *            XML文件路径
     */
    public void writeFile(String out) {
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        DOMSource domSource = new DOMSource(document);
        StreamResult streamResult = new StreamResult(new File(out));
        try {
            Transformer transformer = transformerFactory.newTransformer();
            transformer.transform(domSource, streamResult);
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

public static void main(String[] arg) {
        String in = "xmldemo/BookDOMBulid.xml";
        String out = "xmldemo/BookDOMUpdate.xml";
        BookDOMUpdate bulid = new BookDOMUpdate(in);
        bulid.updateBook("book:author", "王小科", "book:name", "《C#从入门到精通(第1版)》");
        bulid.writeFile(out);
    }
BookDOMUpdate.java
<?xml version="1.0" encoding="UTF-8" standalone="no"?><book:books xmlns:book="http://www.mingrisoft.com"><book:book><book:name>《C#从入门到精通(第1版)》</book:name><book:publisher>清华大学出版社</book:publisher><book:company>明日科技</book:company><book:author>王小科</book:author><book:ISBN>9787302226628</book:ISBN><book:price>69.8</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url></book:book><book:book><book:name>《JavaScript开发技术大全》</book:name><book:publisher>人民邮电出版社</book:publisher><book:company>明日科技</book:company><book:author>梁冰</book:author><book:ISBN>9787115179708</book:ISBN><book:price>65.0</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url></book:book></book:books>
BookDOMUpdate.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><book:books xmlns:book="http://www.mingrisoft.com"><book:book><book:name>《C#从入门到精通(第2版)》</book:name><book:publisher>清华大学出版社</book:publisher><book:company>明日科技</book:company><book:author>王小科</book:author><book:ISBN>9787302226628</book:ISBN><book:price>69.8</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url></book:book><book:book><book:name>《JavaScript开发技术大全》</book:name><book:publisher>人民邮电出版社</book:publisher><book:company>明日科技</book:company><book:author>梁冰</book:author><book:ISBN>9787115179708</book:ISBN><book:price>65.0</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url></book:book></book:books>

实例379  使用DOM删除XML元素
BookDOMDelete.java
    private Document document = null;

private String path = null;

public BookDOMDelete(String path) {
        // TODO Auto-generated constructor stub
        this.path = path;
    }

/**
     * 读取XML文件
     *
     * @param path
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    private void parseReadFile() {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dombuilder = null;
        try {
            dombuilder = documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        File file = new File(path);
        try {
            document = dombuilder.parse(file);
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

/**
     * 根据book子节点的条件删除book节点
     */
    public void deleteBook(String nodeName, String text) {
        parseReadFile();

Element books = document.getDocumentElement();
        NodeList list = document.getElementsByTagName("book:book");
        Node node = null;
        for (int i = 0; i < list.getLength(); i++) {
            NodeList list1 = list.item(i).getChildNodes();
            for (int j = 0; j < list1.getLength(); j++) {
                Node node1 = list1.item(j);
                // 根据条件查询要删除的节点
                if (node1.getNodeName().equals(nodeName)
                        && node1.getTextContent().equals(text)) {
                    node = list.item(i);
                }
            }
        }
        books.removeChild(node);

}

/**
     * 创建XML文件
     *
     * @param node
     *            DOM节点
     * @param url
     *            XML文件路径
     */
    public void writeFile(String out) {
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        DOMSource domSource = new DOMSource(document);
        StreamResult streamResult = new StreamResult(new File(out));
        try {
            Transformer transformer = transformerFactory.newTransformer();
            transformer.transform(domSource, streamResult);
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

public static void main(String[] arg) {
        String in = "xmldemo/BookDOMBulid.xml";
        String out = "xmldemo/BookDOMDelete.xml";
        BookDOMDelete bulid = new BookDOMDelete(in);
        bulid.deleteBook("book:name", "《C#从入门到精通(第2版)》");
        bulid.writeFile(out);
    }
BookDOMDelete.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><book:books xmlns:book="http://www.mingrisoft.com"><book:book><book:name>《JavaScript开发技术大全》</book:name><book:publisher>人民邮电出版社</book:publisher><book:company>明日科技</book:company><book:author>梁冰</book:author><book:ISBN>9787115179708</book:ISBN><book:price>65.0</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url></book:book></book:books>
BookDOMBulid.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><book:books xmlns:book="http://www.mingrisoft.com"><book:book><book:name>《C#从入门到精通(第2版)》</book:name><book:publisher>清华大学出版社</book:publisher><book:company>明日科技</book:company><book:author>王小科</book:author><book:ISBN>9787302226628</book:ISBN><book:price>69.8</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=227</book:url></book:book><book:book><book:name>《JavaScript开发技术大全》</book:name><book:publisher>人民邮电出版社</book:publisher><book:company>明日科技</book:company><book:author>梁冰</book:author><book:ISBN>9787115179708</book:ISBN><book:price>65.0</book:price><book:url>http://www.mingribook.com/bookinfo.php?id=138</book:url></book:book></book:books>

转载于:https://my.oschina.net/MoreYoungGavin/blog/1083425

Java开发实例大全提高篇——XML篇相关推荐

  1. Java开发实例大全(PDF):603个典型事例及源码分析和24个应用方向

    内容简介 <Java开发实例大全(基础卷)>筛选.汇集了Java开发从基础知识到高级应用各个层面约600个实例,每个实例按实例说明.关键技术.设计过程.详尽注释.秘笈心法的顺序进行了分析解 ...

  2. bk3432开发的应用实例_《Javaweb开发实例大全》限时免费啦!

    Java Web,是用Java技术来解决相关web互联网领域的技术栈.web包括:web服务端和web客户端两部分.Java在客户端的应用有Java Applet,不过使用得很少,Java在服务器端的 ...

  3. C#开发实例大全(提高卷)

    下载地址:网盘下载 内容简介  · · · · · · <C#开发实例大全(提高卷)>筛选.汇集了C#开发从基础知识到高级应用各个层面约600个实例及源代码,每个实例都按实例说明.关键技术 ...

  4. PHP开发实例大全(基础卷) 适合菜鸟新手学习

    <PHP开发实例大全(基础卷)>筛选.汇集了PHP开发从基础知识到高级应用各个层面的大量实例及源代码,共有600个左右,每个实例及源代码按实例说明.关键技术.设计过程.详尽注释.秘笈心法的 ...

  5. c51汇编语言典型例子详解,51单片机典型开发实例大全.pdf

    51单片机典型开发实例大全 提供电子技术最新最实用设计方案 --单片机 C51 编程规范 typedef unsigned char INT8U; // 无符号 8 位整型变量 // typedef ...

  6. 《HTML5 开发实例大全》——1.26 使用鼠标光标拖动网页中的文字

    本节书摘来自异步社区<HTML5 开发实例大全>一书中的第1章,第1.26节,作者: 张明星 更多章节内容可以访问云栖社区"异步社区"公众号查看. 1.26 使用鼠标光 ...

  7. 《HTML5 开发实例大全》——1.9 使用 summary 标记元素实现交互

    本节书摘来自异步社区<HTML5 开发实例大全>一书中的第1章,第1.9节,作者: 张明星 更多章节内容可以访问云栖社区"异步社区"公众号查看. 1.9 使用< ...

  8. 《HTML5 开发实例大全》——1.32 在表单中使用 object 元素插入一个Flash

    本节书摘来自异步社区<HTML5 开发实例大全>一书中的第1章,第1.32节,作者: 张明星 更多章节内容可以访问云栖社区"异步社区"公众号查看. 1.32 在表单中使 ...

  9. Android开发实例大全

    <Android开发实例大全> 基本信息 作者: 王东华 丛书名: Android移动开发技术丛书 出版社:电子工业出版社 ISBN:9787121173172 上架时间:2012-8-1 ...

最新文章

  1. JavaScript 高级技巧
  2. 浅析企业网站建设的基本费用组成
  3. Java字节码进制转换
  4. 使用kibana和elasticsearch日志实时绘制图表
  5. 常量池在堆还是方法区_详解Java 虚拟机(第③篇)——String 类和常量池
  6. .net研发工程师面试题,在线交流答案
  7. MySQL实习训练1
  8. Java自带工具包StringUtils包含方法
  9. JavaScript对滚动条的操作
  10. 凯撒密码的实践使用-1
  11. 第13周 本周个人总结
  12. 缺少tlqcu_qcu1.conf文件
  13. postman导入postman_collection文件
  14. MATLAB 中的randn函数
  15. chrome 有哪些有用的插件
  16. qt5 开发及实例(第4版)_才聪学习网_中级微观经济学第4版练习题详解
  17. sap LICENSE KEY和 ACCESS KEY 破解
  18. 讲座报名|美团无人机团队技术分享:大规模、高精度激光SLAM
  19. 长得类似铁甲小宝的机器人_这部特摄剧除了大神以外,女配角也非常养眼,童年只看机器人系列...
  20. [Ec Final 2018] Misunderstood … Missing

热门文章

  1. 五、科大软件工程(孟宁)(5:多线程)
  2. 高级软件工程《软件工程(C编码实践篇)》课程学习心得及内容总结
  3. c语言题库anki,Anki
  4. 基于KNN(K邻近算法)的用电负荷预测(Python代码实现)
  5. Emoji表情符号兼容方案
  6. 村田惯性传感器的行业应用
  7. 一只骡子与软件测试员的故事……
  8. lol盒子皮肤工具 v1.33 免费版
  9. 图像特征提取算法之LBP
  10. CSS中居中的完全指南(中英对照翻译)