달력

4

« 2024/4 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
2007. 2. 15. 19:13

06. XML 문서에 대한 유효성 검증 그거/Tech2007. 2. 15. 19:13

# 유효성 검증(validation)
  미리 정의된 문서의 구조와 XML 문서를 비교하는 작업

1. 기본 DOCTYPE
  DOCTYPE은 XML 문서에 포함되어야 하는 element나 attribute 또는 기타 객체 등을 명시하며, 문서의 상단부에 위치하는 선언부.

  <!DOCTYPE votes [ <!-- definition for element, attribute --> ]>

2. definition for element
  content model : element가 포함하는 요소들고 이 요소들의 정렬 순서, 발생 빈드 등에 대한 정보를 표현
  <!DOCTYPE votes [
   <!ELEMENT votes (voter*)>                votes element는 하나 이상의 voter element를 갖는다.
 <!ELEMENT voter (vote, comments)>        voter element는 vote element와 comments element를 갖는다.
 <!ELEMENT vote (#PCDATA)>                vote element는 일반적인 text나 parsing된 문자 데이터를 포함한다.
 <!ELEMENT comments (#PCDATA)>            comments element는 일반적인 text나 parsing된 문자 데이터를 포함한다.
  ]>

3. definition for attributes
  <!DOCTYPE votes [
     ...
  <!ATTLIST voter personid CDATA #REQUIRED
                  status CDATA "symbiont">
  <!ATTLIST votes totalVotes CDATA #REQUIRED>
  ]>

4. 외부 DTD
  XML 문서와는 별도로 분리된 파일에 문서의 구조 정보들을 포함
  SYSTEM 또는 PUBLIC 식별자에 의해 접근 가능
  <!DOCTYPE votes PUBLIC "-//Vanguard Resort IT//DTD Voting System 2.0//EN"        PUBLIC으로 접근 가능
                         "votes.dtd">                                              SYSTEM으로 접근 가능

# 문서의 유효성 검증

1. SAX 파서의 지원 기능
  SAX의 지원 기능 중 사용 빈도수가 많은 지원 기능
    http://xml.org/sax/features/validation
    http://xml.org/sax/features/namespace (required)
    http://xml.org/sax/features/namespace-prefixes (required)
    http://xml.org/sax/features/external-general-entities
    http://xml.org/sax/features/external-parameter-entities

2. SAX 파서에서의 유효성 검증의 실행

  XMLReader reader = XMLReaderFactory.createXMLReader();
  String featuredId = "http://xml.org/sax/features/validation";
  reader.setFeature(featureId, true); // 유효성 검사 지원 기능을 true로 설정

3. DOM 파서와 유효성 검증
 
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  dbf.setValidating(true);

  이 factory class가 생성하는 모든 파서 객체들은 유효성 검증 property가 true로 설정된다.

4. DOM 파서에 SAX 오류 핸들러 설정

  DocumentBuilder db = dbf.newDocumentBuilder();
  db.setErrorHandler(new ErrorProcessor());


# XML Schema 이용시의 유효성 검증
  XML Schema를 사용하면 DTD에 비해 좀더 쉽고, 유연하며, 강력한 방법으로 유효성을 검증할 수 있다.

1. XML schema의 개요
  XML을 이용해서 XML 문서의 구조를 기술하는 방법을 제공

  XML schema의 예
  <?xml version="1.0"?>
  <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

    <xsd:element name="votes" type="voteType"/>

   <xsd:complexType name="voteType">
     <xsd:sequence>
    <xsd:element name="voter" type="voterType" minOccurs="0" maxOccurs="unbounded"/>
  </xsd:sequence>
        </xsd:attribute name="totalVotes" type="xsd:integer"/>
   </xsd:compexType>

   <xsd:complexType name="voterType">
     <xsd:sequence>
    <xsd:element name="vote" type+"xsd:string"/>
    <xsd:element name="comments" type+"xsd:string"/>
     </xsd:sequence>
  <xsd:attribute name="personid" type="xsd:string"/>
  <xsd:attribute name="status" type="xsd:string"/>
   </xsd:complexType>
  </xsd:schema>

2. XML schema 문서의 명시
  namespace 선언을 위한 attribute를 사용하여 XML schema 문서를 명시한다.

  <votes totalVotes="5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                              xsi:noNamespaceSchemaLocation="votes.xsd">

3. XML Schema에 대한 유효성 검증의 설정
 
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newIntance();
  dbf.setValidating(true);
  dbf.setNamespaceAware(true);
  try {
   dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                  "http://www.w3.org/2001/XMLSchema");
  } catch(IllegalArgumentException e) {
  }


# 오류의 처리

1. 오류와 SAX
  어차피 DOM 파서는 SAX와 관련된 예외 사항을 발생하기 때문에 SAX 관점에서 오류 처리를 한다.
  ErrorHandler를 상속받아 "error, fatalError, warning" method를 override하여 사용한다.

2. 오류의 처리

  try {
    ...
  } catch(Exception e) {
    SAXParseException spe = (SAXParseException)e;

    System.out.println("Problem parsing the file :  + spe.getMessage());
    System.out.println();
    System.out.println("File :  + spe.getSystemId());
    System.out.println("Line number :  + spe.getLineNumber());
    System.out.println("Column number :  + spe.getColumnNumber());
    System.out.println();
  }

3. 문서의 수정
  유효성 검증이 Document 객체에 대한 어떠한 영향력도 갖지 못한다.
  비록 문서가 유효성이 검증되었다 하더라도 Document 객체에 Schema에 위배되는 잘못된 정보를 추가할 수 있다.

  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  dbf.setValidating(true);
  dbf.setNamespaceAware(true);
  try {
   dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                  "http://www.w3.org/2001/XMLSchema");
  } catch(IllegalArgumentException e) {
    ...
  }
  DocumentBuilder db = dbf.newDocumentBuilder();
  db.setErrorHandler(new ErrorProcessor());

  Document doc = db.parse(new File("votes.xml"));

  Element root = doc.getDocumentElement();
  root.appendChild(doc.createTextNode("this node doesn't belong here.")); // Schema 정의에 없는 node를 추가
  System.out.println(root.getLastChild());

  위에서 추가한 text node는 Schema 정의에 존재하지 않는 정보임에도 불구하고, 이 application은 아무런 문제없이 계속 진행할 것이다.
  왜냐하면 이 application의 실행중에는 Document 객체에 대한 유효성을 검증할 방법이 없기 때문이다.


 

'그거 > Tech' 카테고리의 다른 글

08.XML Schema  (0) 2007.02.16
07.DTD(Document Type Definition)  (0) 2007.02.15
05. XML 스트림 (SAX)  (0) 2007.02.14
04. DOM의 활용(고급편)  (0) 2007.02.14
03. XML 문서의 처리 - DOM  (0) 2007.02.14
:
Posted by 뽀기