Wednesday, May 12, 2010

C에서 XML 파싱(libxml2 활용하기)

http://codezip.tistory.com/185


XMLSOFT 사이트
샘플코드 및 API가 잘 나와 있다.

다운받기

버전은 편한 대로 다운 받는다.


리눅스에서는 libxml2-2.6.32.tar.gz 이상없이 설치가 되고
현재 AIX 5.3에서 설치는 되었으나

실행시 라이브러리 참조를 못 하는 듯 하여 RPM를 다운 받아서 설치하였다.

AIX다운받기 설치하였음


./configure; make ; make install
로 쉽게 설치가 된다.

C 소스 작성과 동일하며 컴파일 시에 gcc -Wall -o bpng `xml2-config --cflags` bpng.c



  1. #
  2. #
  3. CC = gcc
  4. DEBUGFLAG = -g
  5. BASEDIR = /home/openbase/wonhong/xml/TEST
  6. CFLAGS = `xml2-config --cflags`
  7. LIBS = `xml2-config --libs`
  8. SRCS = bpng.c
  9. BINS = bpng
  10. $(BINS): $(SRCS)
  11. echo ""
  12. make -f Makefile OBJS=$@.o EXE=$@ build
  13. build: $(OBJS)
  14. $(CC) $(CFLAGS) $(LIBS) -o $(EXE) $(OBJS)





  1. /**
  2. bpng.c
  3. 메뉴얼에 있는 소스를 거의 그대로 사용
  4. XML의 내용만 읽는 기능만 있음
  5. Modified By 일퍼센트
  6. */
  7. #include
  8. #include
  9. #include
  10. #include
  11. #include
  12. #include
  13. void
  14. parseChannel (xmlDocPtr doc, xmlNodePtr cur) {
  15. xmlChar *key;
  16. cur = cur->xmlChildrenNode;
  17. while (cur != NULL) {
  18. if((!xmlStrcmp(cur->name, (const xmlChar *) "item"))) {
  19. parseItem(doc, cur);
  20. }
  21. else if((!xmlStrcmp(cur->name, (const xmlChar *) "title"))) {
  22. key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
  23. printf("BLOG NAME: %s\n", key);
  24. xmlFree(key);
  25. }
  26. else if((!xmlStrcmp(cur->name, (const xmlChar *) "link"))) {
  27. key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
  28. printf("MY BLOG LINK : %s\n", key);
  29. xmlFree(key);
  30. }
  31. cur = cur->next;
  32. }
  33. xmlFreeDoc(doc);
  34. return;
  35. }
  36. void
  37. parseItem(xmlDocPtr doc, xmlNodePtr cur){
  38. xmlChar *key;
  39. cur = cur->xmlChildrenNode;
  40. while (cur != NULL) {
  41. if((!xmlStrcmp(cur->name, (const xmlChar *) "title"))) {
  42. key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
  43. printf("제목: %s\n", key);
  44. xmlFree(key);
  45. }
  46. else if((!xmlStrcmp(cur->name, (const xmlChar *) "description"))) {
  47. key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
  48. printf("내용: %s\n", key);
  49. xmlFree(key);
  50. }
  51. else if((!xmlStrcmp(cur->name, (const xmlChar *) "author"))) {
  52. key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
  53. printf("글쓴이: %s\n", key);
  54. xmlFree(key);
  55. }
  56. else if((!xmlStrcmp(cur->name, (const xmlChar *) "pubDate"))) {
  57. key = xmlNodeListGetString(doc, cur->xmlChildrenNode,1);
  58. printf("등록일자: %s\n", key);
  59. }
  60. cur = cur->next;
  61. }
  62. return;
  63. }
  64. static void
  65. parseDoc(char *docname) {
  66. xmlDocPtr doc;
  67. xmlNodePtr cur;
  68. doc = xmlParseFile(docname);
  69. if (doc == NULL ) {
  70. fprintf(stderr,"Document not parsed successfully. \n");
  71. return;
  72. }
  73. cur = xmlDocGetRootElement(doc);
  74. if (cur == NULL) {
  75. fprintf(stderr,"empty document\n");
  76. xmlFreeDoc(doc);
  77. return;
  78. }
  79. if (xmlStrcmp(cur->name, (const xmlChar *) "rss")) {
  80. fprintf(stderr,"document of the wrong type, root node != rss");
  81. xmlFreeDoc(doc);
  82. return;
  83. }
  84. cur = cur->xmlChildrenNode; //channel
  85. while (cur != NULL) {
  86. if ((!xmlStrcmp(cur->name, (const xmlChar *) "channel"))){
  87. parseChannel (doc, cur);
  88. }
  89. cur = cur->next;
  90. }
  91. xmlFreeDoc(doc);
  92. return;
  93. }
  94. int
  95. main(int argc, char **argv) {
  96. char *docname;
  97. if (argc <= 1) {
  98. printf("Usage: %s docname\n", argv[0]);
  99. return(0);
  100. }
  101. docname = argv[1];
  102. parseDoc (docname);
  103. return (1);
  104. }
  105. string.h>




Rss.xml 파일은

RSS XML 동일한 형태를 가지며 한글은 제외시켜서 테스트하였다.

Libxml2 자체에서 EUC_KR이 인식이 안 되는 듯 하여 iconv 라이브러리 사용해야 할 듯

이거 나중에 올려야겠다.

xml Node Types

Node Types

The following table lists the different W3C node types, and which node types they may have as children:

Node typeDescriptionChildren
DocumentRepresents the entire document (the root-node of the DOM tree)Element (max. one), ProcessingInstruction, Comment, DocumentType
DocumentFragmentRepresents a "lightweight" Document object, which can hold a portion of a documentElement, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
DocumentTypeProvides an interface to the entities defined for the documentNone
ProcessingInstructionRepresents a processing instructionNone
EntityReferenceRepresents an entity referenceElement, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
ElementRepresents an elementElement, Text, Comment, ProcessingInstruction, CDATASection, EntityReference
AttrRepresents an attributeText, EntityReference
TextRepresents textual content in an element or attributeNone
CDATASectionRepresents a CDATA section in a document (text that will NOT be parsed by a parser)None
CommentRepresents a commentNone
EntityRepresents an entityElement, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
NotationRepresents a notation declared in the DTDNone

Node Types - Return Values

The following table lists what the nodeName and the nodeValue properties will return for each node type:

Node typenodeName returnsnodeValue returns
Document#documentnull
DocumentFragment#document fragmentnull
DocumentTypedoctype namenull
EntityReferenceentity reference namenull
Elementelement namenull
Attrattribute nameattribute value
ProcessingInstructiontargetcontent of node
Comment#commentcomment text
Text#textcontent of node
CDATASection#cdata-sectioncontent of node
Entityentity namenull
Notationnotation namenull

NodeTypes - Named Constants

NodeTypeNamed Constant
1ELEMENT_NODE
2ATTRIBUTE_NODE
3TEXT_NODE
4CDATA_SECTION_NODE
5ENTITY_REFERENCE_NODE
6ENTITY_NODE
7PROCESSING_INSTRUCTION_NODE
8COMMENT_NODE
9DOCUMENT_NODE
10DOCUMENT_TYPE_NODE
11DOCUMENT_FRAGMENT_NODE
12NOTATION_NODE

UNIX에서 C를 이용하여 XML 문서 읽기/쓰기 하는 방법

http://blog.paran.com/blog/detail/postBoard.kth?pmcId=highfly&blogDataId=9254191&hrefMark=

Unix에서 C를 이용하여 XML 문서를 read/write 하는 방법입니다.

1. libxml2 설치.

http://xmlsoft.org/downloads.html > ftp://xmlsoft.org/libxml2/

에서 적당한 버전을 다운 받아서

> gzip -d libxml2-2.6.11.tar.gz

> tar xvf libxml2-2.6.11.tar

libxml2-2.6.11.tar > configure

libxml2-2.6.11.tar > make

libxml2-2.6.11.tar > make install

을 차례로 실행 하여 설치한다.

2. 예제 컴파일

reader 예제: http://xmlsoft.org/examples/reader1.c

writer 예제: http://xmlsoft.org/examples/testWriter.c

로컬로 파일을 만들고,

라이브러리 path가 없으면 설정해 주고,

export LD_LIBRARY_PATH=/usr/local/lib:.

컴파일 한다.

gcc -I /usr/local/include/libxml2 -lxml2 reader1.c

a.out이 나오면 동작 확인

reader: a.out FILE.xml

writer: a.out

* 참고.

2.6.11 version은 "euc-kr"로 인코딩 된 문서는 동작 하지 않는군요.

높은 버전은 되려나..? 어떤 설정이 필요한가..?



Tuesday, May 11, 2010

tar 사용법

  • 인터넷 여기저기서 오려붙였습니다. :) 자꾸 까먹는지라... :(

설명

  • tar?타 또는 타르는 지정된 여러 개의 파일들을 아카이브라고 부르는 하나의 파일로 만들거나, 하나의 아카이브 파일에 집적되어 있는 여러 개의 파일을 원래의 형태대로 추출해내는 유닉스 쉘명령어이다. tar 아카이브 파일에는 어떻게 파일명을 적든상관없지만, tar 로 묶었다는 것을 분명히 해주기 위해 ".tar"라는 파일이름 확장자가 붙는다. tar 아카이브 파일 내에 들어있는 파일들은 압축되는 것이 아니라, 단지 하나의 파일로 모아지는 것뿐이다.

tar라는 이름은 파일들이 주로 자기테이프에 백업되고, 이따금씩 검색되기도 하던 때로부터 유래하였다. 그러나, 요즘에는 tar 아카이브가 오히려 유닉스 시스템들간에 파일들을 전송하기 위해 좀더 자주 사용되고 있다.

자주사용되는 조합

압축하기

> tar -cvzf tarfile.tar.gz ./ 
  • -c : tar 화일을 생성한다.
  • -v : 생성되는 화일 절차를 보여준다.
  • -f : backup 화일명을 지정 한다. Default는 "/dev/rmt0"이다.
  • -z : gzip에 현재 tar를 넘겨 압축한다.

퍼미션 유지하며 압축하기

> tar -cvzp tarfile.tar.gz ./ 

압축풀기

> tar -xvfz tarfile.tar.gz ./ 

퍼미션 유지하며 압축풀기

> tar -xvfzp tarfile.tar.gz ./ 

내용 보기 및 테스트

> tar -tvfz tarfile.tar  
  • -t : tar화일의 목차를 보여준다.

업데이트

> tar -uvfz tarfile.tar reverse.c 
tar 화일 끝에 reverse.c가 변경 되었으면 추가 한다.

[Linux] scp 사용하기

[Linux] scp 사용하기
※상황 - 개발 서버에서 작업하던 내용을 로컬로 받아야 될 경우


scp [계정]@[서버주소]:[소스경로] [받을경로]
scp에 -r 옵션을 주어 디렉토리를 받을 수도 있다

예를 들어)
scp jhcho@cdev1.embider.com:/home/tftp/hddapps_KT_$FIRMWARE.tar.gz ~/MegaTV/USBFirmware/
거꾸로 해도 됨. 즉, 로컬의 파일을 원격지로 보낼 수도 있다.

예를 들어)
scp /home/xxxx/test.txt xxxx@xxx.xxx.xxx.xxx:/home/xxxx