'JAVA'에 해당되는 글 60건

  1. 2010.06.30 [sample] class 파일 버전 확인하기 1
  2. 2010.06.30 정규표현식 / xmlHeader 정보 제거하기
  3. 2010.05.07 쿠키를 다루는 여러가지 방법
  4. 2010.03.24 java File 다루기 / 용량만큼 파일 자르기 및 용량이하는 파일 덧붙이기
  5. 2010.03.19 정규표현식 / <img , <a 를 변환해보자.
  6. 2010.03.17 오래기다렸다!! htmlUnit 2.7 1
  7. 2009.12.09 System 시간
  8. 2009.08.25 JAVA 버전별 다운로드 1
  9. 2008.10.16 dom4j 파싱 / 생성 3
  10. 2008.04.18 XSL (eXtensible Stylesheet Language) 이란? 2


생성된 class 파일의 버전을 몰라 애먹는 경우가 있어 구해놓습니다.
보통의 class 파일은 우리가 알고있는 이상의 로그정보를 가지고 있습니다.
주석, 컴파일된 내용 등등..
class를 날렵하게 생성하신다면 javac 당시에 옵션! 주는거 잊지 마세요.

import java.io.*;

public class ClassVersionChecker {
    public static void main(String[] args) throws IOException {
        for (int i = 0; i < args.length; i++)
            checkClassVersion(args[i]);
    }

    private static void checkClassVersion(String filename)
        throws IOException
    {
        DataInputStream in = new DataInputStream
         (new FileInputStream(filename));

        int magic = in.readInt();
        if(magic != 0xcafebabe) {
          System.out.println(filename + " is not a valid class!");;
        }
        int minor = in.readUnsignedShort();
        int major = in.readUnsignedShort();
        System.out.println(filename + ": " + major + " . " + minor);
        in.close();
    }
}



[^>]*xml[^>]*.?.*true[^>]>


<?xml version="1.0" encoding="utf-8" ?><blog type="tattertools/1.1" migrational="true"><setting>..........</setting>

위에 노란색의 정규 표현식으로 xml Header에 위치한 문자열을 찾는 방법입니다.
본 정규표현식에 중요한 사항은 2개의 xml블럭을 잡는것이 이슈였는데 *.?.* 이 그역할을 톡톡히 해주었네요.

 바보같이 보이겠지만 쿠키를 다루는 여러가지 방법이 있는 이유는
쿠키를 내가 받아서 다른 서버에 넘겨야 하는 이슈가 있기 때문입니다.
 CGI도 있겠고 JAVA도 있고 Apache도 있는데 여기서 각기 다른 원하는 형태와 버전의 이슈가 있습니다.


 

// httpClient2.x 에서 지원되는 방식
HttpClient client = new HttpClient();
PostMethod httppost = new PostMethod(POSTING_URL);
httppost.setRequestHeader("User-Agent", "Nozilla 9.9");
httppost.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
httppost.setRequestHeader("Cookie", msg.getSenderCookieString());


// httpClient2.x 에서 지원되는 방식
HttpState clientstate = new HttpState();
clientstate.addCookies(msg.getSenderCookieOrg());
clientstate.setCookiePolicy(CookiePolicy.COMPATIBILITY);
client.setState(clientstate);




// HttpClient 3.x 버전부터 지원되는 로직입니다. ymko
httppost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
httppost.addRequestHeader("COOKIE", msg.getSenderCookie());



아울러 쿠키는 jdk 쿠키와 apache 쿠키가 다르다. 이에 대한 변환과정을 만들어 두는것도 좋다.


지원기능 :  파일분할, 파일존재유무, 파일폴더 존재유무, 생성할 파일이 이미 존재 확인, 크기확인..

아래 예제는 객체 정보를 파일로 생성하는데 있어서 2M의 MAX 크기를 기본으로 설정하고
2M가 넘으면 새로운 파일을 만들어내는 로직이다.

다소 위험한 부분들도 있지만 (특히 NumberFormatException) 이런 취약부분은 코드가 길어지는
관계로 생략하고, 파일이 생성되야 하는 폴더에 생성이되고 증가되면서 임계치를 넘었는지 봐서
다음번 파일 생성시에는 이름을 달리해서 생성시키는 방법을 가지고 있다.

이런로직의 핵심은    OutputStream os = new FileOutputStream(neoPathFile, addFile);  로써
addFile true 라면 덧붙이기가 가능하고 false면 새롭게 생성하게 된다.
이미 단위메소드 활용법에 대해서는 알고 있을테지만 종합선물셋트 형태에서는 고민할꺼리가 많아지는터라 이렇게 정리를 해본다.

 public static String  makeFileOneContents(String fileName,  String serviceRoot, XMLHeaderBean xmlUserInfo, List<XMLCategoryBean>  xmlCategory,  XMLPostBean postBean,  NeoBean neoBean) {
  boolean makeFileBoolean = false;
  boolean addFile = false;
  String neoFileName = fileName;
  
  String neouserFileRoot = serviceRoot+File.separator+neoBean.getName()();
  long maxFileSize = 2 * 1024 * 1024; // 2M
  long nowFileSize = 0; // 2M

  File fileDirRoot = new File (neouserFileRoot);

  if (fileDirRoot.isDirectory()) {  // 디렉토리 존재하는가? / 네 존재합니다.
   File[] files = fileDirRoot.listFiles();
   
   for (File fileDir : files) {
          String fileNames = fileDir.getName();
          long file_size = fileDir.length();

          if (fileNames.equals(neoFileName+".xml") && file_size >= maxFileSize) {
           int fileCount = Integer.parseInt(neoFileName.substring(neoFileName.lastIndexOf("_")+1, neoFileName.length())) + 1;
           neoFileName = neoFileName.substring(0, neoFileName.lastIndexOf("_")) +"_"+fileCount;
          } else {
           nowFileSize = files.length;
           addFile = true;
          }
      }
  } else {
   fileDirRoot.mkdir();
  }
  
  String neoPath = serviceRoot+File.separator+neoBean.getName()()+File.separator+neoFileName;
  neoPath = neoPath +".xml";  // 넘어올때 xml이라는 확장자 이름을 달고오지 않습니다.
    
  File neoPathFile = new File(neoPath);
  XMLBean xmlBean = new XMLBean();

  BufferedReader in = null; 
  BufferedWriter out = null;
  try {
   OutputStream os = new FileOutputStream(neoPathFile, addFile);  //addFile의 옵션에 따라 파일을 덧 추가하거나 분할한다. (true: 추가 / false : 분할) 
   out = new BufferedWriter (new OutputStreamWriter(os, "UTF-8"));
   
   // XML을 만들때 setting + category 를 1개의 Set으로 간주해서 우선 파일을 생성합니다.
   // 그리고 postAL 의 경우는 attach된 파일이 있을경우를 대비 1개씩 추가로 삽입합니다.
   String readLine;
   String readSetting = xmlUserInfo.getXml().toString();
   StringBuffer sbCate = new StringBuffer();
   for (XMLCategoryBean categoryBean: xmlCategory) {
    sbCate.append(categoryBean.getXml());   
   }
   readSetting = readSetting+sbCate.toString(); // setting + category
   
   if (!addFile) {  // 새로만든 파일은 해더와 카테고리 정보를 넣습니다. 
    out.write(xmlBean.getHeader());
    in = new BufferedReader (new InputStreamReader(new ByteArrayInputStream(readSetting.getBytes())));
    while ((readLine = in.readLine()) != null) {
     out.write(readLine);
     out.newLine();
    }
   }
      
   if (postBean != null) {
    nowFileSize  =+ postBean.getXml().toString().getBytes().length;
    in = new BufferedReader (new InputStreamReader(new ByteArrayInputStream(postBean.getXml().toString().getBytes())));
    while ((readLine = in.readLine()) != null) {
     out.write(readLine);
     out.newLine(); 
    }     
   }
 
   makeFileBoolean = true;
   
   if (nowFileSize >= maxFileSize) {  // 생성될 파일의 크기가 크다면 Footer 정보를 넣어줍니다.
    out.write(xmlBean.getFooter());
   }   
  }
  catch (MalformedURLException e) { e.printStackTrace(); }
  catch (IOException e) { e.printStackTrace(); }
  finally {
       try {
    in.close();
    out.close();
   } catch (IOException e) { e.printStackTrace(); }
  }  
  return neoFileName;
 }
}





content.replaceAll("(?i)<img[^>]*"+fileUrl+"[^>]*.?>", sb.toString());
content.replaceAll("(?i)<a[^>]*"+fileUrl+"[^>]*.?>[^>]*.?[^>]*.?</a>", sb.toString());



늘 그렇지만
난 먹기 편한 음식이 좋다.
코드를 찾을때도 마찬가지 인것 같다.
좀 정형화 된것이다 싶을때는 있는것 쓰는게 좋을것 같다.

위의 2개의 구문은 html안에 img, a 가 들어있을때 원하는 구문 형태로 변경하는것이다.
물론 본문안에 있는 fileUrl은 해당 파일 명에 해당한다.

어떤가? 한번 test 해보시기 바란다.
아참 test 방법은 html 코드를 EditPlus에 넣고 해보면 된다.
혹시나 몰라서 하는말인데.. 꼭 찾을때는 [Regular expression] 을 체크하고 찾기 바란다.

 


사실 더이상 개발이 안되는줄 알았다.
UX의 비중높은 WEB환경의 변화와 ActiveX가 결코 htmlUnit을 호락호락하게
놔둘것 같지 않았기 때문이다.
그런데 2010년02월09일 전격적으로 발표가 났다!!

"javaScript 지원 Native ActiveX 지원"

정말 수고 많았다. 너의 자랑스런 탄생을 기반삼아 이제 새로운 WEB을 보일때가 된것 같구나!
웃샤!!
버닝이다.

System 시간

JAVA/sample JAVA 2009. 12. 9. 15:57

long neouser = System.currentTimeMillis();


이분.. 매번 찾으려 들면 잘 안떠올라 T-T

JAVA 버전별 다운로드

JAVA 2009. 8. 25. 16:27

http://java.sun.com/products/archive/


너무 간단한가?
하지만 역시나 찾으려 들면 찾기 어렵다.
특히 이전에 사용하던 JDK같은 경우에는 더 그런것 같다 ^^

dom4j 파싱 / 생성

JAVA 2008. 10. 16. 21:52

XML 파싱

dom4j를 이용하여 쉽게 XML을 파싱 할 수 있습니다.
[ 예제 코드 ]
import java.net.URL;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
public class Foo {
    public Document parse(URL url) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(url);
        return document;
    }
}


Iterator 사용하기

"document"(SAXReader나 DocumentHelper를 통해 만들어진 XML객체)는 자바의 표준 Iterator를 이용하여 다양한 방법으로 네비게이션 할 수 있다.
[ 예제 코드 ]
public void bar(Document document) throws DocumentException {

        Element root = document.getRootElement();

        // 루트 엘리먼트의 자식노드 반복
        for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
            Element element = (Element) i.next();
            // do something
        }

        // 루트의 엘리먼트 중 "foo"라는 이름을 갖는엘리먼트의 자식노드 반복
        for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {
            Element foo = (Element) i.next();
            // do something
        }

        // 루트의 어트리뷰트 반복
        for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
            Attribute attribute = (Attribute) i.next();
            // do something
        }
     }


XPath를 이용한 강력한 네비게이션

dom4j의 XPath 표현들로 document 트리 내 어떤 노드들도 접근할 수 있다.(Attribute, Element or ProcessingInstruction).
 복잡한 네비게이션을 한줄로 할 수 있다.
[ 예제 코드 ]
public void bar(Document document) {
    List list = document.selectNodes( "//foo/bar" );
    Node node = document.selectSingleNode( "//foo/bar/author" );
    String name = node.valueOf( "@name" );
}


XHTML 문서의 링크 네이게이션 예

[ 예제 코드 ]
public void findLinks(Document document) throws DocumentException {
    List list = document.selectNodes( "//a/@href" );
    for (Iterator iter = list.iterator(); iter.hasNext(); ) {
        Attribute attribute = (Attribute) iter.next();
        String url = attribute.getValue();
    }
}


XPath를 배우려면 Zvon tutorial 튜토리얼 참조하세요.  


빠른 반복

커다란 XML tree 전체 iterator를 만들어 가면서 네비게이션 하려면 성능이 떨어지기 때문에 빠른 반복을 할 수 있는 메소드를 사용한다. (treeWalk를 주목)
[ 예제 코드 ]
public void bar(Document document) {
    List list = document.selectNodes( "//foo/bar" );
    Node node = document.selectSingleNode( "//foo/bar/author" );
    String name = node.valueOf( "@name" );
}
public void treeWalk(Document document) {
    treeWalk( document.getRootElement() );
}
public void treeWalk(Element element) {
    for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
        Node node = element.node(i);
        if ( node instanceof Element ) {
            treeWalk( (Element) node );
        }
        else {
            // do something....
        }
    }
}

 
새 XML문서 생성

[ 예제 코드 ]
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class Foo {
    public Document createDocument() {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement( "root" );
        Element author1 = root.addElement( "author" )
            .addAttribute( "name", "James" )
            .addAttribute( "location", "UK" )
            .addText( "James Strachan" );
       
        Element author2 = root.addElement( "author" )
            .addAttribute( "name", "Bob" )
            .addAttribute( "location", "US" )
            .addText( "Bob McWhirter" );
        return document;
    }
}


문서를 파일로 쓰기

Document나 어떤 노드에서도 write()메소드를 이용하여 FileWriter로 쓸수 있다.
FileWriter out = new FileWriter( "foo.xml" );
document.write( out );

XMLWriter를 이용하여 출력 포맷을 변경할 수 있다.

[ 예제 코드 ]
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class Foo {
    public void write(Document document) throws IOException {
        // lets write to a file
        XMLWriter writer = new XMLWriter(
            new FileWriter( "output.xml" )
        );
        writer.write( document );
        writer.close();

        // Pretty print the document to System.out
        OutputFormat format = OutputFormat.createPrettyPrint();
        writer = new XMLWriter( System.out, format );
        writer.write( document );
        // Compact format to System.out
        format = OutputFormat.createCompactFormat();
        writer = new XMLWriter( System.out, format );
        writer.write( document );
    }
}


Document를 문자열로 문자열을 Document로

Document나 어떤 노드에서나 asXML()메소드를 호출하여 쉽게 xml문자열을 추출할 수 있다.
Document document = ...;
String text = document.asXML();   
또한 valid한 xml문자열을 DocumentHelper를 이용하여 Document 객체로 만들수 있다.
String text = "<person> <name>James</name> </person>";
Document document = DocumentHelper.parseText(text);

XSLT를 이용한 문서 스타일 적용

Sun의 JAXP API를 사용하여 쉽게 XSLT를 적용할 수 있다.
Xalan, SAXON과 같은 어떠한 XSLT을 가지고도 작업 할수 있다.

[ 예제 코드 ]
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import org.dom4j.Document;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;
public class Foo {
    public Document styleDocument(
        Document document,
        String stylesheet
    ) throws Exception {
        // load the transformer using JAXP
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(
            new StreamSource( stylesheet )
        );
        // now lets style the given document
        DocumentSource source = new DocumentSource( document );
        DocumentResult result = new DocumentResult();
        transformer.transform( source, result );
        // return the transformed document
        Document transformedDoc = result.getDocument();
        return transformedDoc;
    }
}



XSL (eXtensible Stylesheet Language) 이란?


XML 문서를 presentation 해주기 위한 포맷팅 언어.

xml 문서이다.

1. XSL 의 구성

1) XSLT ( XSL Transformation )
   : xml 문서의 구조를 다른 구조로 변환하기 위한 마크업 언어.
2) XPath ( XSL Path Language )
   : xml 문서 내에서 특정 part (엘리먼트 or 속성)을 찾아가기 위한 경로 표기 언어.
3) XSL-FO ( XSL Formatting Objects )
   : Formatter 프로그램을 통해 XML 문서를 비 XML 문서로 변환하기 위한 마크업 언어.


2. XSL 처리 과정

▪ Transformation : XML 문서를 다른 구조의 XML 문서로 구조를 변환하는 과정.
▪ Formatting       : XML 문서를 특정 S/W, H/W에 맞는 비 XML 문서로 변환하는 과정.

사용자 삽입 이미지

XSL Transform 의 결과물은 파일 형태의 문서가 아닌, 메모리 상에서 트리를 이루는 DOM 객체들로 생성된다. 이것을 Result Tree 라 한다.

3. XSLT 문서의 구성

▪ XML 선언 (optional)
▪ XSLT stylesheet 선언
▪ Top-level element
▪ Template과 Literal result element



◆ XSL 문서의 루트 엘리먼트와 최상위 엘리먼트

1. Root Element
: stylesheet or transform

 

<?xml version="1.0" encoding="euc-kr"?>                

<xsl:stylesheet

version="1.0"                          

xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 

</xsl:stylesheet>


▪ version 필수 선언.
http://www.w3.org/1999/XSL/Transform : XSLT 1.0 의 public namespace URI
  cf. http://www.w3.org/1999/TR/WD-xsl  :  XSLT 1.0 공식 권고안이 나오기 이전 MS에서 사용하던 것.

2. Top-level Element
: 루트 엘리먼트의 자식 엘리먼트

-  xsl 문서의 결합
▪  import 엘리먼트
▪  include 엘리먼트


- result tree 문서 종류 결정
▪ output 엘리먼트

- result tree의 엘리먼트 내용을 담고 있는 Top-level Element
▪ template 엘리먼트

- 기타
▪ strip-space 엘리먼트
▪ preserve-space 엘리먼트
▪ key 엘리먼트
▪ decimal-format 엘리먼트
▪ namespace-alias 엘리먼트
▪ attribute-set 엘리먼트
▪ variable 엘리먼트
▪ param 엘리먼트





◆ output 엘리먼트

: Result Tree 의 문서 종류를 지정한다.
  생략되었거나, 있어도 method 속성이 없으면
  default 값은 xml이다.
  ( result tree 의 root element 이름이 namespace 접두사가 없는 'html'일 경우에만 default 값이 'html' )

<xsl:output 속성명="속성값" 속성명="속성값"/>

ex.
<xsl:output method="xml" version="1.0" encoding="euc-kr" indent="yes"/>



속 성 명

  

속성값 유형

method

Result tree 문서 종류 지정

xml, html, text

version

Result tree XML 문서일 경우 XML 권고안 버전

1.0

encoding

Result tree의 인코딩 방식 지정

String(ex:euc-kr,UTF-8)

omit-xml-declaration

Result tree XML 선언 생략 여부.
출력 방법이 'xml'이면 default는 'no'

yes, no

standalone

Result tree의 외부 문서 참조 여부

yes, no

doctype-public

Result tree가 문서 유형 선언을 포함할 경우 PUBLIC 식별자 지정

String

doctype-system

Result tree 가 문서 유형 선언을 포함할 경우 SYSTEM 식별자 지정

String

cdata-section-elements

Result tree에서 CDATA 섹션으로 사용되어야 할 노드 지정
method="xml" 인 경우만 해당.

Qname

indent

Result tree에 화이트스페이스(태그와 태그 사이의 공백)를 포함할 지 여부

yes, no

media-type

media-type 지정

String



사용자 삽입 이미지















 

◆ 노드 및 노드셋


XML 문서

<?xml version=”1.0”>

<musiclist>

     <title>사랑 하나면 돼</title>

<title>착한 거짓말</title>

<title>물끄러미</title>

</musiclist>

루트 노드 : 문서 자체를 뜻하는 노드

 

루트 엘리먼트 노드

title  

    title     노드 셋 : 같은 엘리먼트 이름을 가진 노드들.

    title                   

 

 




Template Rule


어떤 구조를 다른 구조로 바꾸는 방법.

▪ 원본 XML 문서의 노드(엘리먼트)들을 다른 구조의 노드(엘리먼트)로 바꾸는 역할.


1. 정의
==============================================================================================


<xsl:template match="pattern">   

             <!-- Content: (xsl:param*, template) -->

</xsl:template>

ex.

        <xsl:template match="//book">       ← XSLT 엔진이 소스 트리에서 <book> 엘리먼트 발견할    

             .....                                            때마다 처리한다. node-set에 템플릿 룰을 적용해 변환.

        </xsl:template>


▪ match 속성 : 소스 트리의 하나의 패턴을 규정한다.
                     패턴에 매치하는 어떤 노드에도 적용될 수 있다.

▪ pattern : XML 문서에서 변환되어야 할 대상 노드 지정.

              Xpath 표현식 중, 한 개 노드 or 노드셋을 가리키는 표현식.

   

   

/

루트 노드(문서 자체) 지정.

/노드명/…/노드명

특정 경로의 노드() 지정.

//노드명 or 노드명

경로 상관없이 같은 이름의 노드() 지정.

/노드명/노드명[@속성명=’속성값’]

특정 속성값을 가지는 노드() 지정.

/노드명/노드명[@속성명!=’속성값’]

특정 속성값과 다른 속성값을 가지는 노드() 지정.


▪ Xpath expression Vs Xpath pattern

)  /name/first


1) Xpath express : document root 로 가서 <name> 자식 요소를 찾은 후, <first> 자식 요소로 가라
2) Xpath pattern  : <name> 요소의 한 자식인 어떤 <first> 요소와 일치시켜라. 이것은 document root 의 자식이어야 한다.



2. 적용

==============================================================================================
: 템플릿 룰을 통해 변환된 result tree의 어떤 부분에 포함할 것인지 알려준다.
 
 

<xsl:apply-templates select="node-set-expression">

              <!-- Content: (xsl:sort | xsl:with-param)* -->
<xsl:apply-templates>

ex. <xsl:apply-templates select="book">


▪ select 속성 : 모든 children을 처리하는 대신 선택된 노드만 처리한다.

▪ XSL 변환기의 동작

① select 속성에 지정된 노드와 동일한 노드를 match 속성으로 갖는 템플릿 룰을 찾는다.
② 템플릿 룰을 적용해 변환된 내용을 xsl:apply-templates 엘리먼트와 대치시킨다.

③ select 속성 생략시, 모든 템플릿 룰을 적용해 변환된 내용을 xsl:apply-templates 엘리먼트와 대치시킨다.


3. name 속성
==============================================================================================
: XSL 문서내에서 반복 적용되는 내용을 한 개의 템플릿 룰로 만들고,

  그 템플릿 룰명으로 다른 템플릿 룰에서 참조해서 적용할 경우에 사용된다.
 
템플릿 룰은 match와 name 속성 중 하나를 반드시 기술해야 한다.

1) 정의

<xsl:template name="Template Rule name">

                   <!-- Content: (xsl:param*, template) -->

</xsl:template>


ex.

<xsl:template name="tYear">

         <font color="red">2007년</font>
</xsl:template>  


2) 적용

<xsl:call-template name="Template Rule name">

             <!-- Content: xsl:with-param* -->
<xsl:call-template/>

ex. <xsl:call-template name="tCompany"/>



4. priority 속성
==============================================================================================
: XML 문서의 대상 노드를 변환시키는 템플릿 룰이 여러 개 있을 경우 우선선위가 높은 템플릿 룰이 적용되도록 한다.

priority number 가 클 수록 우선순위가 높다.

name 속성을 갖는 template rule 에서는 사용할 수 없다.


<xsl:template match="pattern" priority="number”>

         <!-- Content: (xsl:param*, template) -->
</xsl:template>


ex.

<xsl:template match="musiclist" priority="1”>

<th>title</th>

</xsl:template>

 

<xsl:template match="/musiclist /music" priority="2">

<th>price</th>

</xsl:template>



5. mode 속성
==============================================================================================
: 소스 트리의 같은 부분이 한 번 이상 처리되어야 할 때 사용한다.
name 속성을 갖는 template rule 에서는 사용할 수 없다.  (match 속성만 가능)

1) 정의

<xsl:template match="pattern" mode="Mode Name">

             <!-- Content: (xsl:param*, template) -->

</xsl:template>


ex.

<xsl:template match="title" mode="modeA">

               <xsl:value-of select="author"/>

</xsl:template>


2) 적용

<xsl:apply-templates select="node-set-expression" mode="Mode Name"/>


ex.
<xsl:apply-templates select="/musiclist/title[@genre=
jazz']" mode="modeA"/>

<xsl:apply-templates select="/musiclist/title[@genre=dance']" mode="modeB"/>





◆ XML 문서의 내용 가져오기


1. 엘리먼트의 컨텐트 내용 or 속성값 가져오기 : value-of

==============================================================================================

1) 엘리먼트의 컨텐트 내용 가져오기

<xsl:template match="대상 노드">

               <xsl:value-of select="대상 노드 자신 or 자식 노드명"
                                 disable-output-escaping="yes or no"/>

</xsl:template>

ex.
<xsl:template match="/musiclist/music">

               <xsl:value-of select="."/>          // title 노드 자신의 컨텐트 내용을 가져와 대치한다.

</xsl:template>


<!-- 컨텐트 내용이 숫자일 경우 -->
<xsl:template match="/musiclist/music">

               <xsl:value-of select="format-number(price, '###,###')"/>         
</xsl:template>



2) 속성값 가져오기

<xsl:template match="대상 노드">

               <xsl:value-of select="@속성명"/>

</xsl:template>

ex.
<xsl:template match="/musiclist/music">

               <xsl:value-of select="@genre"/>        
</xsl:template>


disable-output-escaping 속성
: XSLT processor 에게 이스케이프 문자 ("&amp;", "&lt;") 대신 "&", "<" 문자를 출력하라고 지시한다.
  default는 'no' 로, 보통은 XSLT processor가 출력시 자동으로 이런 문자로 바꾸어준다.
  xsl:value-of 와 xsl:text 엘리먼트의 속성으로 사용된다.

ex. <name>&amp;</name>

<xsl:value-of select="name" disable-output-escaping="yes"/>

→ 결과는 &

<xsl:value-of select="name" disable-output-escaping="no"/>

→ 결과는 &amp;




2. 엘리먼트 or 속성 복사해서 가져오기 : copy-of
==============================================================================================
: 원본 XML 문서의 일부분을 구조 변경 없이 복사해서 변환될 XML 문서에 붙인다.

<xsl:template match="대상 노드">

               <xsl:copy-of select="(복사할)자식노드명 or @속성명"/>

</xsl:template>

ex.

<xsl:template match="music">

               <xsl:copy-of select="title"/>

               <xsl:copy-of select="@genre"/>
</xsl:template>



◆ 정렬 (Sort)

<xsl:apply-templates select="대상 노드">

        <xsl:sort select="자식노드명 or @속성명"
                     data-type="number | text"
                     order="ascending | descending"
                     case-order="upper-first | lower-first"/>

</xsl:apply-templates>


ex.

<xsl:apply-templates select="/musiclist/music">

          <xsl:sort select="price" data-type="number" order="ascending"/>

</xsl:apply-templates>


default
   data-type : text
   order : ascending
   case-order : document에 사용되는 언어를 정의하는 lang 속성에 의존.
                     (upper-first일 경우 "A B a b" -> "A a B b")
▪ xsl:apply-templates 엘리먼트와 xsl:for-each 엘리먼트의 자식엘리먼트로 작성된다.

▪ 2차 정렬
: 1차로 컬럼을 먼저 정렬시키고, 정렬된 상태에서 다른 컬럼을 2차로 정렬시키는 것.

<xsl:apply-templates select="/musiclist/music">

              <!-- 1차 정렬 -->

              <xsl:sort select="@genre"/>

              <!-- 2차 정렬 -->

              <xsl:sort select="price" data-type="number" order="ascending"/>

</xsl:apply-templates>





◆ 번호 매기기

: XSL 변환기는 result tree 생성시 자동으로 번호를 매겨 삽입할 수 있다.
  이 기능을 이용해 XSL 문서에서 번호가 삽입되는 위치에 xsl:number 엘리먼트를 작성한다.

<xsl:template match="대상 노드">
              <xsl:number format="
번호 형식">
</xsl:template>

ex.
<xsl:template match="music">
   <tr>
      <td><xsl:number format="1"></td>
      <td><xsl:value-of select="title"></td>
   </tr>             
</xsl:template>


번호 형식 : '1', 'a', 'A', 'i', 'I', '(1)'




◆ 제어 엘리먼트


1. xsl:if 엘리먼트
==============================================================================================
: 조건식이 참이면 변환 내용을 적용한다.

<xsl:template match="xml 대상 노드">

        <xsl:if test="조건식">

                   <!-- Content: template -->
     
</xsl:if>

</xsl:template>


▪ 조건식에 자주 오는 XPath 표현식

조건식

설명

노드명=’문자열

컨텐트 내용이 문자열을 가지면 참

@속성명=’속성값

주어진 속성값을 가지면 참

@속성명!=’속성값

주어진 속성값이 아닌 다른 값을 가지면 참

start-with(노드명,’문자열’)

컨텐트 내용이 문자열로 시작하면 참

contains(노드명,’문자열’)

컨텐트 내용이 문자열을 포함하면 참




2. xsl:choose 엘리먼트
==============================================================================================

<xsl:template match="music">
     
<xsl:choose>
           
<xsl:when test="조건식1">       

                  <!-- Content: template -->
           
</xsl:when>

                           
           
<xsl:when test="조건식2">

                  <!-- Content: template -->           
            </xsl:when>

                         
           
<xsl:otherwise>                    <!-- 생략 가능 -->

                   <!-- Content: template -->
           
</xsl:otherwise>
     
</xsl:choose>

</xsl:template>

test 표현 중 하나라도 참이 되면 <xsl:choose>를 빠져나간다.


3. xsl:for-each 엘리먼트
==============================================================================================
: 대상 노드 숫자만큼 반복해서 변환시킨다.
  반드시 템플릿 룰 안에서 작성되어야 한다.

<xsl:template match="대상 노드">

     <xsl:for-each select="대상 노드">

       변환 내용
     </xsl:for-each>
</xsl:template>


ex.
<xsl:for-each select="/musiclist/music">

<tr>

<td><xsl:value-of select="title"/></td>

<td><xsl:value-of select="@genre"/></td>

</tr>

</xsl:for-each>





◆ 변수와 파라미터


1. 변수
==============================================================================================

1) 변수 선언

<xsl:variable name="변수명" select="변수값"/> 

<xsl:variable name="변수명">변수명</xsl:variable>

<!-- 변수값으로 빈 문자값을 줄 경우 -->
<xsl:variable name="변수명" select="''"/> 
<xsl:variable name="변수명"/>

ex.

<xsl:variable name="vList" select="'책목록'"/>  <!--select 속성값 지정시, 문자열인 경우 반드시 ''-->

<xsl:variable name="vKind">
       <!-- Content: template -->
</xsl:variable>



2) 변수 사용
▪ 변수값(=단순한 문자열) & result tree의 컨텐트 내용으로 사용될 경우

<엘리먼트> <xsl:value-of select="$변수명"/> </엘리먼트>

ex.
  <xsl:template match="music">
             <xsl:value-of select="$변수명"/>
      </xsl:template>


▪ 변수값(=단순한 문자열) & result tree의 속성값으로 사용될 경우

속성명="{$변수명}"

ex.
<font size="{$vGenre}"> .... </font>


▪ 변수값(=단순한 문자열) & XPath 표현식에서 사용될 경우

[노드명=$변수명] or [@속성명=$변수명]

ex.
<xsl:for-each select="//music[@genre=$vGenre]">


▪ 변수값이 result tree의 일부분을 이루는 엘리먼트들로 구성되어 있을 경우

<엘리먼트> <xsl:copy-of select="$변수명"/> </엘리먼트>

ex. <xsl:copy-of select="$vSize"/>



3) 변수 사용 범위
▪ global variable : top-level Element 로 작성. Template Rule 위에 작성해도 좋고, 아래에 작성해도 좋다.
▪ local variable : Template Rule 내에서 작성


4) 변수 예제
▪ xml 예제

more..


▪ xsl 예제

<?xml version="1.0" encoding="euc-kr"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 

 <!-- 글로벌 변수 선언  -->

 <xsl:variable name="vList" select="'쇼핑목록'"/>

 <xsl:variable name="vKind">computer</xsl:variable>

 <xsl:variable name="vSize" select="10"/>

 <xsl:variable name="vCompany">

       <font color="blue">Cheap</font> Company
 </xsl:variable>

 

 <!-- 시작 템플릿   -->

 <xsl:template match="/">

    <html>

       <body>

          <!-- 컨텐트 내용으로 사용  -->

          <h2><xsl:value-of select="$vList"/></h2> 

                   

          <!-- XPath 표현식에서 사용 -->

          <xsl:for-each select="//product[@kind=$vKind]">

                          

             <!-- 속성값으로 사용  -->

             <font size="{$vSize}"> 

                 <xsl:value-of select="title"/>

             </font>

             <br/>

          </xsl:for-each>

                   

           <!-- result tree 일부분을 이루는 엘리먼트로 구성될 변수값 사용 -->

          <xsl:copy-of select="$vCompany"/>

       </body>

</html>

</xsl:template>

</xsl:stylesheet>


▪ 결과
사용자 삽입 이미지

▪ <xsl:copy-of select="$vCompany"/> → <xsl:value-of select="$vCompany"/> 로 변경하면
font가 적용되지 않고 텍스트만 결과로 출력된다.


2. 파라미터
==============================================================================================

: 현재 템플릿 룰에서 다른 템플릿 룰을 적용할 때 전달하고 싶은 데이터가 있을 경우

1) 파라미터 선언

<xsl:param name="파라미터명" select="파라미터값"/> 

<!-- 파라미터값으로 빈 문자값을 줄 경우 -->
<xsl:param name="파라미터명" select="''"/> 
<xsl:param name="파라미터명"/>


2) 파라미터 전달

▪ xsl:with-param 엘리먼트는 xsl:apply-templates엘리먼트와 xsl:call-template 엘리먼트의 자식 엘리먼트로 작성된다.

▪ select 속성값으로 엘리먼트 노드, 텍스트 노드 모두 가능하다.
  또한 꼭 소스 트리에서 올 필요는 없고, 문자열을 넘겨도 좋다.
  ex. 엘리먼트 노드일 때 : <xsl:with-param name="pTitle" select="title"/>
        텍스트 노드일 때   : <xsl:with-param name="pTitle" select="title/text()"/>
        문자열일 때           : <xsl:with-param name="pTitle" select="'문자열 파라미터이다'"/>
   
▪ xsl:apply-templates엘리먼트 : match 속성 갖는 다른 템플릿 룰을 적용
<xsl:apply-templates match="대상 노드">
        <xsl:with-param name="파라미터명" select="전달할 데이터"/>
</
xsl:apply-templates>


▪ xsl:call-templates엘리먼트   : name 속성 갖는 다른 템플릿 룰을 적용

<xsl:call-template name="Template Rule name">
        <xsl:with-param name="파라미터명" select="전달할 데이터"/>
</
xsl:apply-template>


3) 파라미터 사용

<xsl:template ~>
       <!-- 파라미터 선언 -->
      <xsl:param name="파라미터명"/>
       <!-- 파라미터 사용 -->
         .....
<xsl:template>


4) 예제

<xsl:template match="book">

          <!-- 파라미터 값 전달 -->

          <xsl:call-template name="tBook">

                  <xsl:with-param name="pTitle" select="title"/>

          </xsl:call-template>

</xsl:template>

 

<xsl:template name="tBook">

          <!-- 파라미터 선언 -->

          <xsl:param name="pTitle"/>   
         
<!-- 파라미터 사용 -->       
         
<xsl:value-of select="$pTitle"/>

</xsl:template>





◆ XSL 문서의 결합

: 외부 XSL 문서를 참조

1. xsl:include 엘리먼트
==============================================================================================
: Top-level 엘리먼트로서 작성된다.
  다른 Top-level 엘리먼트 (ex. Template Rule) 의 정의가 앞이나 뒤에 있어도 상관 없다.
<xsl:include href="uri-reference"/>



2. xsl:import 엘리먼트
==============================================================================================
: 다른 Top-level 엘리먼트보다 먼저 작성되어야 한다.
  여러 개 작성할 수 있다.

<xsl:import href="uri-reference"/>


▪ 참조하는 문서와 참조되는 문서에 같은 match 속성값이 정의되어 있을 경우,
  참조하는 XSL 문서의 Template Rule 이 적용된다.

1 2 3 4 5 6 

글 보관함

카운터

Total : / Today : / Yesterday :
get rsstistory!