XSD、XSLT、DOM4J解析XML

xml文件 000.xml

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="000.xsl"?>
<addresses>
 <value>
  <no>A100</no>
  <addr>上单位dd</addr>
 </value>
 <value>
  <no>A101</no>
  <addr>ss撒发达</addr>
 </value>
</addresses>

xsd文件 000.xsd

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

 <xs:element name="addresses">
  <xs:complexType>
   <xs:sequence>
    <xs:element name="value" maxOccurs="unbounded">
     <xs:complexType>
      <xs:sequence>
       <xs:element name="no" type="xs:string" />
       <xs:element name="addr" type="addr" />
      </xs:sequence>
     </xs:complexType>
    </xs:element>
   </xs:sequence>
  </xs:complexType>
 </xs:element>


 <xs:simpleType name="addr">
  <xs:restriction base="xs:string">
   <xs:minLength value="1" />
   <xs:maxLength value="5" />
  </xs:restriction>
 </xs:simpleType>

</xs:schema>
xslt文件 000.xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <!-- XSLT 语法参考w3cschool -->
 <xsl:template match="/">
  <html>
   <head>
    <title>First XSLT example</title>
   </head>
   <body>
    <p>
     <table border='1'>
      <xsl:for-each select="addresses/value">
       <tr>
        <td>
         <xsl:value-of select="no" />
        </td>
        <td>
         <xsl:value-of select="addr" />
        </td>
       </tr>
      </xsl:for-each>
     </table>
    </p>
   </body>
  </html>
 </xsl:template>
</xsl:stylesheet>

bean文件 XmlBean.java

package com.zht.bean;
public class XmlBean {
    private String no;  
    private String addr;  
    public String getNo() {  
        return no;  
    }  
    public void setNo(String no) {  
        this.no = no;  
    }  
    public String getAddr() {  
        return addr;  
    }  
    public void setAddr(String addr) {  
        this.addr = addr;  
    }  
    @Override 
    public String toString() {  
        return "编号:" + this.no + ",地址:" + this.addr;  
    }  
}
路径文件 ReadXmlFileStream.java

package com.zht.xml;
import java.io.InputStream;
public class ReadXmlFileStream {
  private static final String XML_FILE = "com/zht/bean/000.xml"; 
  private static final String XSD_FILE = "com/zht/bean/000.xsd"; 
  private static final String XSL_FILE = "com/zht/bean/000.xsl";   
  private static final String HTML_FILE = "com/zht/bean/001.HTML";
     public static InputStream getXmlFileStream() {   
         return Thread.currentThread().getContextClassLoader()   
                 .getResourceAsStream(XML_FILE);   
     }
  public static String getXML_FILE() {
   return XML_FILE;
  }
  public static String getXSD_FILE() {
   return XSD_FILE;
  }
  public static String getXSL_FILE() {
   return XSL_FILE;
  }
  public static String getHTML_FILE() {
   return HTML_FILE;
  }   
}
解析xml文件 DOM4JParseXml.java

package com.zht.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Iterator;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXValidator;
import org.dom4j.io.XMLWriter;
import org.dom4j.util.XMLErrorHandler;

import com.zht.bean.XmlBean;

public class DOM4JParseXml {
  private static XmlBean address = new XmlBean();   
    
     public static void main(String[] args) {   

//     读取XML文件内容 
//      ---====================读xml文件========================================
         long starttime = System.currentTimeMillis();   
   
         try {   
             InputStream in = ReadXmlFileStream.getXmlFileStream();   
   
             Reader reader = new InputStreamReader(in, "utf-8"); // 注意编码问题   
   
             SAXReader SaxReader = new SAXReader();   
             Document doc = SaxReader.read(reader);   
             Element root = doc.getRootElement();   
             Element childNode = null;   
//           枚举名称为value的节点   
             for (Iterator<Element> it = root.elementIterator("value"); it.hasNext();) {   
                 childNode = (Element) it.next();   
                 address.setNo(childNode.elementText("no"));   
                 address.setAddr(childNode.elementText("addr"));   
                 System.out.println(address);   
             }   
         } catch (Exception e) {   
             e.printStackTrace();   
         }   
         System.out.println("运行时间:" + (System.currentTimeMillis() - starttime) + " 毫秒");   
//    ---============================================================
        
//     写XML文件内容 
         try {
    testWrite();
   } catch (Exception e) {
    e.printStackTrace();
   }
        
//      XML经XSD文件进行校验
         validateXMLByXSD();
            
//      XML经XSLT转换为HTML文件
      String xml = ReadXmlFileStream.getXML_FILE();
      String xsl = ReadXmlFileStream.getXSL_FILE();
      String out = ReadXmlFileStream.getHTML_FILE();
      xsl(xml,out,xsl);
   
     } 
    

     /**  
      * 写XML  
      */  

     public static void testWrite() throws Exception{
        
         Document document = DocumentHelper.createDocument();
        
         Element root = document.addElement("root");
        
         Element element1 = root.addElement("user")
         .addAttribute("name","Alexander")
         .addAttribute("blog", "http://netnova.blogjava.net")
         .addText("我是中文的名字");

        
         XMLWriter writer = new XMLWriter(new FileOutputStream("com/zht/bean/001.xml"));
        
         writer.write(document);
         writer.close();   
         System.out.println("写XML文件成功~!");
     }

 

     /**  
      * 通过XSD(XML Schema)校验XML  
      */ 
     public static void validateXMLByXSD() {  
         String xmlFileName = ReadXmlFileStream.getXML_FILE();  
         String xsdFileName = ReadXmlFileStream.getXSD_FILE();  
         try {  
             //创建默认的XML错误处理器   
             XMLErrorHandler errorHandler = new XMLErrorHandler();  
             //获取基于 SAX 的解析器的实例   
             SAXParserFactory factory = SAXParserFactory.newInstance();  
             //解析器在解析时验证 XML 内容。   
             factory.setValidating(true);  
             //指定由此代码生成的解析器将提供对 XML 名称空间的支持。   
//             factory.setNamespaceAware(true);  
             //使用当前配置的工厂参数创建 SAXParser 的一个新实例。   
             SAXParser parser = factory.newSAXParser();  
             //创建一个读取工具   
             SAXReader xmlReader = new SAXReader();  
             //获取要校验xml文档实例   
             Document xmlDocument = (Document) xmlReader.read(new File(xmlFileName));  
             //设置 XMLReader 的基础实现中的特定属性。核心功能和属性列表可以在 [url]http://sax.sourceforge.net/?selected=get-set[/url] 中找到。   
             parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");  
             parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:" + xsdFileName);  
             //创建一个SAXValidator校验工具,并设置校验工具的属性   
             SAXValidator validator = new SAXValidator(parser.getXMLReader());  
             //设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。   
             validator.setErrorHandler(errorHandler);  
             //校验   
             validator.validate(xmlDocument);  
  
             XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());  
             //如果错误信息不为空,说明校验失败,打印错误信息   
             if (errorHandler.getErrors().hasContent()) {  
                 System.out.println("XML文件通过XSD文件校验失败!");  
                 writer.write(errorHandler.getErrors());  
                 System.out.println(errorHandler.getErrors().asXML());
                
             } else {  
                 System.out.println("Good! XML文件通过XSD文件校验成功!");  
             }  
         } catch (Exception ex) {  
             System.out.println("XML文件: " + xmlFileName + " 通过XSD文件:" + xsdFileName + "检验失败。\n原因: " + ex.getMessage());  
             ex.printStackTrace();  
         }  
     }  
  

     /**  
      * 通过XSL生成HTML文件

      */  
     public static void xsl(String inFilename, String outFilename,
   String xslFilename) {
  try {
   TransformerFactory factory = TransformerFactory.newInstance();

   Templates template = factory.newTemplates(new StreamSource(
     new FileInputStream(xslFilename)));

   Transformer xformer = template.newTransformer();

   Source source = new StreamSource(new FileInputStream(inFilename));
   Result result = new StreamResult(new FileOutputStream(outFilename));

   xformer.transform(source, result);
   System.out.println("生成html成功~!");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

 

 

你可能感兴趣的:(html,xml,bean,sun,XSL)