Tuesday, May 04, 2010

StudyNote--III DML--JAVA DOM XML

import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.lang.*;
import javax.xml.xpath.*;

public class DOMSearch{
public static void main(String[] arg) throws NullPointerException{
String SeriesName=null;
  if (arg.length >= 1) {
     SeriesName = arg[0];
//In Java whether input has double quotation marks or not,the outputs are the same
}else if(arg.length==0){
         System.out.println("No Series name input");
}
try{
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
//Specifies that the parser produced by this code will provide support for XML namespaces,never forget this
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("TVGuide.xml");
doc.normalize();
/*可以去掉XML文档中作为格式化内容的空白而映射在DOM树中的不必要的Text Node对象。否则你得到的DOM树可能并不如你所想象的那样。特别是在输出的时候,这个normalize()更为有用*/
XPathFactory xpathFactory=XPathFactory.newInstance();
XPath xpath=xpathFactory.newXPath();
NodeList list1=doc.getElementsByTagName("Program");
  String Name="TVGuide/Channel/Program[Series='"+SeriesName+"']/../Name/text()";
/*To combine some string for the coming XPath Search,also we can use other ways to combine strings,like StringBuilder and StringBuffer
Examples: String Name=new StringBuffer().append("TVGuide/Channel/Program[Series='").append(SeriesName).append("']/../Name/text()").tostring();
This example use toString() to convert StringBuffer to String in case Name can be used in the next xpath.evalute which needs String value
String Name=new StringBuilder().append("TVGuide/Channel/Program[Series='").append(SeriesName).append("']/../Name/text()").tostring();
This is the same as the StringBuffer example
StringBuffer is thread-safe and better to be used in multi-threads while StringBuilder is not thread-safe and it has better to be used in single-thread as it is fast.
*/
      NodeList nodelist=(NodeList)xpath.evaluate(Name,doc,XPathConstants.NODESET);
      if(nodelist.getLength()==0){
      System.out.println("Series '"+SeriesName+"' Not Found");
      }else{
      for(int i=0;i<nodelist.getLength();i++){
      System.out.println(nodelist.item(i).getNodeValue());
      String StartTime="TVGuide/Channel[Name='"+nodelist.item(i).getNodeValue()+"']/Program[Series='"+SeriesName+"']/Start/text()";
      NodeList nodelist1=(NodeList)xpath.evaluate(StartTime,doc,XPathConstants.NODESET);
      for(int j=0;j<nodelist1.getLength();j++){
  System.out.println(nodelist1.item(j).getNodeValue());
       }
      }
     }
}catch(Exception e){
e.printStackTrace();
}
}
}

Labels: , ,

StudyNote--IV DML--JAVA SAX XML

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;
import java.util.regex.*;
<copyright(c) by sksc.me>
<No one can just copy and paste these codes without permission by sksc.me before 1st June 2010>
public class SAXPrint extends DefaultHandler{
   private int indent=0;
   private int CountStart=0;
   private int CountEnd=0;
   public void PrintIndent(){
  for(int i=0;i<indent;i++){
  System.out.print("|");
  }
   }
   public void startDocument() throws SAXException{
/*Here comes to a basic question.Throw is used to actually throw the exception, whereas throws is declarative for the method. They are not interchangeable.* /
  System.out.println("Orders.xml");
   }
   public void startElement(String NameSpaceURI,String LocalName,String QName,Attributes attrs)throws SAXException{
          CountStart++;
  CountEnd=0;
  if(CountStart>=2){
  System.out.print("\n");
  }
   PrintIndent();
System.out.print("+-"+QName);
  if(attrs.getValue(0)!=null){
  System.out.print("  (");
  for(int i=0;i<attrs.getLength();i++){
  System.out.print(" "+attrs.getQName(i)+"="+attrs.getValue(i));
  if(i!=attrs.getLength()-1){System.out.print(",");}
  }
  System.out.print(" )");
  }
  indent++;
   }
   public void characters(char ch[], int start, int length) throws SAXException{
String data=new String(ch,start,length);
Pattern  p= Pattern.compile("\\S+?\\s");
/*This is to use java pattern match to find the long string where there is at least a whitespace inside, and only extract the first word.\\S means all kind of characters while ? means non-greedy,and \\s is representing whitespace*/
    Matcher match = p.matcher(data);
    if(match.find(0)) {
/*match.find(0) is the first word that matches the pattern,that is all what we need,enough.*/
        String MatchWord = match.group().trim();
        System.out.print(":"+MatchWord+"...");
    }else  if(!data.trim().equals(""))
       System.out.print(":"+data.trim());
/*This function returns a string with leading and trailing whitespace omitted*/
      }
   }
   public void endElement(String NameSpaceURI,String LocalName,String QName) throws SAXException{
indent--; CountStart=0; CountEnd++; if(CountEnd>=2){ System.out.print(""); }else{System.out.println();} }
   public void endDocument() throws SAXException{
   }
    public static String FileCheck(String arg) throws IOException{
  Pattern  pattern= Pattern.compile("\\S+?\\.xml");
  Matcher matcher = pattern.matcher(arg);
  if(!matcher.find()){
  System.out.println("Wrong FileExtension");
  System.exit(0);
  }
  else if(!(new File(arg)).exists()){
  System.out.println("The File Does Not Exist");
  System.exit(0);
  }
return arg;
   }
   public static void main(String arg[]) throws SAXException, IOException, ParserConfigurationException{
          if(arg.length==0){
  System.out.println("No FileName Input");
  System.exit(0);
  }
  String FileName=FileCheck(arg[0]);
  XMLReader xmlReader=XMLReaderFactory.createXMLReader();
  xmlReader.setContentHandler(new SAXPrint());
  xmlReader.parse(new InputSource(FileName));
/*This is one of  the way to read  XML file to memory.There are three ways to set up a SAX  Parser
(1)XMLReader reader=XMLReaderFactory.createXMLReader();//This is what I am using
(2)XMLReader reader=XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
To code in this way,one should have had a certain class org.apache.xerces.parsers.SAXParser in class path and imported it.Otherwise it will throw a java.lang.ClassNotFoundException;
(3)DefaultHandler handler = new SAXPrint(); // Use the default (non-validating) parser
  SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidting(true);
/*Non-validating can be used if the file is well-formed,it works without regard to the actual content.On the other hand,a validating parser reads the DOCTYPE declaration and retrieves a file of definitions called DTD for the data.File can also be described with XML schema,but the syntax is different*/
try {
  SAXParser saxParser = factory.newSAXParser();
  saxParser.parse(new File("orders.xml"), handler ); 
  } catch (Throwable t) {
    t.printStackTrace();
  }
*/
}
}

Labels: , , ,

Thursday, April 29, 2010

StudyNote--II DML--XML HTML CSS XPath XSLT


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XSLSchema-instance">
<xsl:output method="html"/>
<xsl:template match="Dictionary">
<html>
     <head>
       <link rel="stylesheet" href="dictionary.css" type="text/css"/>
<!--在html文件中加入link标签,利用link标签调用外部CSS样式文件,还可以利用<div>在html内部定义样式,或者利用<style>标签在头部定义调用,或者可以利用@import外部调用-->
       <title>Bilingual Lexion <xsl:value-of select="/Dictionary/from"/>--<xsl:value-of select="Dictionary/to"/></title>
     </head>
     <body>
       <h1>Browse by letter</h1>
       <table border="0" id="table1">
<!--可以在定义table标签的时候为其加上id号,类似于table的名字,用以区分不同的table,以便于CSS样式表中对于不同的table定义样式-->
         <tr>
            <xsl:for-each select="/Dictionary/translation">
                <xsl:sort select="@initial" data-type="number"/>

<xsl:if test="generate-id(.)=generate-id(../translation[@initial=current()/@initial])">
<!--利用generate-id()函数返回唯一节点标识指定节点的字符串值,可以利用这个等式得到重复节点的名字-->
                   <td>
                      <p><a href="{concat('#',@initial)}">
<!--文件内跳转函数的前部分,原始href="#jump"缺点是无法重复定义链接点,利用concat连接字符串,href={concat('#',string)}可以重复循环定义链接点,每次只要保证string不同即可。也可以利用href="#{generate-id()}",完成相同的功能。但是如果一个链接点对应多个链接目的点,只会跳转到最近的那个目的点-->
                     <xsl:value-of select="@initial"/></a></p>
                   </td>
                </xsl:if>
            </xsl:for-each>
         </tr>
        </table>
        <xsl:for-each select="/Dictionary/translation">
           <xsl:sort select="@initial" data-type="number"/>

<xsl:if test="generate-id(.)=generate-id(../translation[@initial=current()/@initial])">
<h3><p><a name="{@initial}"><xsl:value-of select="@initial"/></a></p></h3>
<!--文件内跳转目的点,引用@initial的值,与href 呼应,使得每次跳转到不同的目的点-->
           <table border="1" width="700" id="table2">
              <xsl:for-each select="../translation[@initial=current()/@initial]">
              <xsl:sort select="search"/>
              <xsl:sort select="replace"/>
               <tr>
                  <th align="left" width="350"><xsl:value-of select="search"/></th>
                  <td width="350">
                     <xsl:for-each select="/Dictionary/translation[search=current()/search]/replace">

<xsl:if test="position()!=last()"><xsl:copy-ofselect="."/><xsl:text>;</xsl:text></xsl:if>
<xsl:if test="position() =last()"><xsl:copy-of select="."/><xsl:text></xsl:text></xsl:if>
<!--copy-of 和value-of在此处功能一样,都是显示当前节点的replace的值,利用position()和last()测试当前节点是否是最后的节点,并采取相应的操作-->
<--此处还可以利用aply-templates模板自动匹配replace,同样可以正确的显示出replace值如下

   <td  class="replace"><xsl:apply-templates select="replace"/></td>
                                                   ................................................
                                                           ..............................
                                                              ......................






<xsl:template match="replace">
         <xsl:value-of select="."/>
          <xsl:if test="position() !=last()"><xsl:text>;</xsl:text></xsl:if>
</xsl:template>

.......................
....................--->


                     </xsl:for-each>
                  </td>
               </tr>
             </xsl:for-each>
            </table>
         </xsl:if>
        </xsl:for-each>
     </body>
</html>    
</xsl:template>
</xsl:stylesheet>

************************************************************
get <xsl:apply-templates select="replace">example from my friend WYL thanks here....

Labels: , , , , ,

StudyNote--I DML--XML XPath XSLT

<?xml version="1.0" encoding="UTF-8"?>
<!--copyright(c) by sksc.me -->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="wordlist">
<Dictionary xsi:noNamespaceSchemaLocation="translation.xsd">
<!--noNamespaceSchemaLocation可以作为Dictionary的属性赋值-->
   <from>
     <xsl:value-of select="upper-case(/wordlist/@from)" />
   </from>
   <to>
     <xsl:value-of select="upper-case(/wordlist/@to)"/>
   </to>
   <total>
    <xsl:value-of select="count(/wordlist/wordEntry/search[not(.=following::search)])"/>
   </total>
  <xsl:for-each select="/wordlist/wordEntry">
   <xsl:sort select="search"/>
    <xsl:if test="generate-id(.)=generate-id(../wordEntry[search=current()/search])">
          <xsl:element name="translation">
              <xsl:attribute name="initial">
                <xsl:value-of select="substring(search,1,1)"/>
                <!--get the first letter of search term as the content of initial -->
              </xsl:attribute>            
              <xsl:element name="search">
                 <xsl:value-of select="search"/>
              </xsl:element>
              <counter>
                <xsl:value-of select="count(../wordEntry[search=current()/search][not(.=following::wordEntry)])"/>
              </counter>
              <xsl:for-each select="../wordEntry[search=current()/search][not(.=following::wordEntry)]">
                    <xsl:sort select="replace"/>
                 <xsl:copy-of select="replace"/>
              </xsl:for-each>
          </xsl:element>
     </xsl:if>
  </xsl:for-each>
</Dictionary>
</xsl:template>
</xsl:stylesheet>

Labels: , , , , ,