Expat+SCEW-操弄XML的瑞士刀

本文介绍如何利用Expat+SCEW工具库轻松读写XML文件。通过简单的API即可实现创建复杂的XML结构及解析,适用于各种XML处理场景。
订阅所有程式设计的网志  订阅 |  上一篇  上一篇 |  返回  返回 |  下一篇  下一篇
  程式设计
09
04

Expat+SCEW-操弄XML的瑞士刀

之前处理XML文件时,就是用这套工具横行江湖,Expat提供细致的函式读写xml文件,SCEW则是把Expat函式包装成亮丽的界面供使用者更方便的存取xml,个人觉的,这两套函式库实在不输给.net System.xml下的API

首先下载expat libraryscew library ,这两套软体的使用方式很简单,执行configure,make,make install后,就可以使用它们的library,而我这边的范例编译时用static link,所以我都直接连接它们的.a函式库档

Makefile的范例如下

  1. ALL : example  
  2.  
  3. example : example . c  
  4. $ ( CC ) - I ./ scew - 0.4.0 / scew / - o   example example . c libscew . a libexpat . a  
  5. clean :
  6. rm   example

SCEW write xml的方法大概就五组API如下 
(1)创造xml tree: tree = scew_tree_create(); 
(2)加入root element: scew_tree_add_root(scew_tree*, char*); 
(3)加入root element的子element: scew_element_add(scew_element*,char*); 
(4)加入element attribute: scew_element_add_attr_pair(scew_element*, char*, char*);; 
(5)加入element content: scew_element_set_contents(scew_element*, char *);

写入xml文件的范例如下

  1. int CreateXML ()  
  2. {  
  3. scew_tree * tree = NULL ;
  4. scew_element * root = NULL ;
  5. scew_element * element = NULL ;
  6. scew_element * sub_element = NULL ;
  7. scew_element * sub_sub_element = NULL ;
  8. scew_attribute * attribute = NULL ;
  9.  
  10. tree = scew_tree_create () ;
  11. root = scew_tree_add_root ( tree , " scew_test " ) ;
  12.  
  13. /* Add an element and set element contents. */  
  14. element = scew_element_add ( root , " element1 " ) ;
  15. scew_element_set_contents ( element , " element contents. " ) ;
  16.  
  17. /* Add an element with an attribute pair (name, value). */  
  18. element = scew_element_add ( root , " element2 " ) ;
  19. scew_element_add_attr_pair ( element , " attribute " , " value " ) ;
  20.  
  21. element = scew_element_add ( root , " element3 " ) ;
  22. scew_element_add_attr_pair ( element , " attribute1 " , " value1 " ) ;
  23. /**
  24. * Another way to add an attribute. You loose attribute ownership,
  25. * so there is no need to free it.
  26. */  
  27. attribute = scew_attribute_create ( " attribute2 " , " value2 " ) ;
  28. scew_element_add_attr ( element , attribute ) ;
  29.  
  30. element = scew_element_add ( root , " element4 " ) ;
  31. sub_element = scew_element_add ( element , " sub_element1 " ) ;
  32. scew_element_add_attr_pair ( sub_element , " attribute " , " value " ) ;
  33.  
  34. sub_element = scew_element_add ( element , " sub_element2 " ) ;
  35. scew_element_add_attr_pair ( sub_element , " attribute1 " , " value1 " ) ;
  36. scew_element_add_attr_pair ( sub_element , " attribute2 " , " value2 " ) ;
  37.  
  38. sub_sub_element = scew_element_add ( sub_element , " sub_sub_element1 " ) ;
  39. scew_element_add_attr_pair ( sub_sub_element , " attribute1 " , " value1 " ) ;
  40. scew_element_add_attr_pair ( sub_sub_element , " attribute2 " , " value2 " ) ;
  41. scew_element_add_attr_pair ( sub_sub_element , " attribute3 " , " value3 " ) ;
  42. /* Check attribute2 replacement. */  
  43. scew_element_add_attr_pair ( sub_sub_element , " attribute2 " , " new_value2 " ) ;
  44. scew_element_set_contents ( sub_sub_element , " element contents. " ) ;
  45.  
  46. scew_writer_tree_file ( tree , " example.xml " ) ;
  47. scew_tree_free ( tree ) ;
  48.  
  49. return   0 ;
  50. }

执行范例会制造出如下内容的xml

  1. <? xml version = " 1.0 " encoding = " UTF-8 " standalone = " no " ?>
  2.  
  3. < scew_test >
  4. < element1 > element   contents .</ element1 >
  5. < element2   attribute = " value " />
  6. < element3   attribute1 = " value1 " attribute2 = " value2 " />
  7. < element4 >
  8. < sub_element1   attribute = " value " />
  9. < sub_element2   attribute1 = " value1 " attribute2 = " value2 " >
  10. < sub_sub_element1   attribute1 = " value1 " attribute2 = " new_value2 " attribute3 = " value3 " > element contents .</ sub_sub_element1 >
  11. </ sub_element2 >
  12. </ element4 >
  13. </ scew_test >

而SCEW读取xml的方法大约有6组API 
(1)创造xml parser: parser = scew_parser_create; 
(2)读入xml档案: scew_parser_load_file(scew_parser*,char*) 
(3)读出element name: scew_element_name(scew_element*) 
(4)读出element attribute: scew_attribute_next(scew_element*, scew_attribute*) 
(5)读出element content: scew_element_contents(scew_element*) 
(6)寻找子element: scew_element_next(scew_element*, scew_element*)

读取xml文件的范例如下

  1. void print_attributes ( scew_element * element )  
  2. {  
  3. scew_attribute * attribute = NULL ;
  4.  
  5. if   ( element != NULL )  
  6. {  
  7. /**
  8. * Iterates through the element's attribute list, printing the
  9. * pair name-value.
  10. */  
  11. attribute = NULL ;
  12. while   (( attribute = scew_attribute_next ( element , attribute )) != NULL )  
  13. printf ( " %s= \ " % s \ "" , scew_attribute_name ( attribute ) , scew_attribute_value ( attribute )) ;
  14. }  
  15. }  
  16.  
  17.  
  18.  
  19. int   PrintElement ( scew_element * element )  
  20. {  
  21. scew_element * child = NULL ;
  22. XML_Char   const * contents = NULL ;
  23.  
  24. printf ( " element name: %s " , scew_element_name ( element )) ;
  25. print_attributes ( element ) ;
  26. contents = scew_element_contents ( element ) ;
  27. if   ( contents == NULL )  
  28. printf ( " \ n \ n " ) ;
  29. else   printf ( " \ n%s content:%s \ n \ n " , scew_element_name ( element ) , contents ) ;
  30.  
  31. /**
  32. * Call print_element function again for each child of the
  33. * current element.
  34. */  
  35. while   (( child = scew_element_next ( element , child )) != NULL )  
  36. PrintElement ( child ) ;
  37.  
  38. return   0 ;
  39.  
  40. }  
  41. int   ReadXML ()  
  42. {  
  43. scew_tree * tree = NULL ;
  44. scew_parser * parser = NULL ;
  45. scew_element * element = NULL ,* parent = NULL ;
  46. /**
  47. * Creates an SCEW parser. This is the first function to call.
  48. */  
  49. parser = scew_parser_create () ;
  50. scew_parser_ignore_whitespaces ( parser , 1 ) ;
  51. if   ( ! scew_parser_load_file ( parser , " example.xml " )) return 0 ;
  52. tree = scew_parser_tree ( parser ) ;
  53. PrintElement ( scew_tree_root ( tree )) ; //traverse all child and siblings of tree
  54. /* Remember to free tree (scew_parser_free does not free it) */  
  55. scew_tree_free ( tree ) ;
  56.  
  57. /* Frees the SCEW parser */  
  58. scew_parser_free ( parser ) ;
  59. return   0 ;

完整的范例程式请点此下载

  标签: linux 
评论: 0 |引用: 0 |阅读: 5740
conda update -n base -c conda-forge conda --yes Solving environment: failed CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.com/pkgs/free/linux-64/repodata.json.bz2> Elapsed: - An HTTP error occurred when trying to retrieve this URL. HTTP errors are often intermittent, and a simple retry will get you on your way. If your current network has https://www.anaconda.com blocked, please file a support request with your network engineering team. ConnectionError(MaxRetryError("HTTPSConnectionPool(host='repo.anaconda.com', port=443): Max retries exceeded with url: /pkgs/free/linux-64/repodata.json.bz2 (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x2b165a4e3128>: Failed to establish a new connection: [Errno -2] Name or service not known'))")) [scb3201@ln137%bscc-a6 ~]$ # 测试安装常用包 [scb3201@ln137%bscc-a6 ~]$ conda install -c conda-forge numpy pandas Solving environment: failed CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.com/pkgs/r/noarch/repodata.json.bz2> Elapsed: - An HTTP error occurred when trying to retrieve this URL. HTTP errors are often intermittent, and a simple retry will get you on your way. If your current network has https://www.anaconda.com blocked, please file a support request with your network engineering team. ConnectionError(MaxRetryError("HTTPSConnectionPool(host='repo.anaconda.com', port=443): Max retries exceeded with url: /pkgs/r/noarch/repodata.json.bz2 (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x2ba3d9347be0>: Failed to establish a new connection: [Errno -2] Name or service not known'))")) [scb3201@ln137%bscc-a6 ~]$ [scb3201@ln137%bscc-a6 ~]$ # 检查环境状态 [scb3201@ln137%bscc-a6 ~]$ conda list --revisions 2018-11-08 03:08:33 (rev 0) +_ipyw_jlab_nb_ext_conf-0.1.0 +alabaster-0.7.11 +anaconda-5.3.1 +anaconda-client-1.7.2 +anaconda-navigator-1.9.2 +anaconda-project-0.8.2 +appdirs-1.4.3 +asn1crypto-0.24.0 +astroid-2.0.4 +astropy-3.0.4 +atomicwrites-1.2.1 +attrs-18.2.0 +automat-0.7.0 +babel-2.6.0 +backcall-0.1.0 +backports-1.0 +backports.shutil_get_terminal_size-1.0.0 +beautifulsoup4-4.6.3 +bitarray-0.8.3 +bkcharts-0.2 +blas-1.0 +blaze-0.11.3 +bleach-2.1.4 +blosc-1.14.4 +bokeh-0.13.0 +boto-2.49.0 +bottleneck-1.2.1 +bzip2-1.0.6 +ca-certificates-2018.03.07 +cairo-1.14.12 +certifi-2018.8.24 +cffi-1.11.5 +chardet-3.0.4 +click-6.7 +cloudpickle-0.5.5 +clyent-1.2.2 +colorama-0.3.9 +conda-4.5.11 +conda-build-3.15.1 +conda-env-2.6.0 +constantly-15.1.0 +contextlib2-0.5.5 +cryptography-2.3.1 +curl-7.61.0 +cycler-0.10.0 +cython-0.28.5 +cytoolz-0.9.0.1 +dask-0.19.1 +dask-core-0.19.1 +datashape-0.5.4 +dbus-1.13.2 +decorator-4.3.0 +defusedxml-0.5.0 +distributed-1.23.1 +docutils-0.14 +entrypoints-0.2.3 +et_xmlfile-1.0.1 +expat-2.2.6 +fastcache-1.0.2 +filelock-3.0.8 +flask-1.0.2 +flask-cors-3.0.6 +fontconfig-2.13.0 +freetype-2.9.1 +fribidi-1.0.5 +get_terminal_size-1.0.0 +gevent-1.3.6 +glib-2.56.2 +glob2-0.6 +gmp-6.1.2 +gmpy2-2.0.8 +graphite2-1.3.12 +greenlet-0.4.15 +gst-plugins-base-1.14.0 +gstreamer-1.14.0 +h5py-2.8.0 +harfbuzz-1.8.8 +hdf5-1.10.2 +heapdict-1.0.0 +html5lib-1.0.1 +hyperlink-18.0.0 +icu-58.2 +idna-2.7 +imageio-2.4.1 +imagesize-1.1.0 +incremental-17.5.0 +intel-openmp-2019.0 +ipykernel-4.9.0 +ipython-6.5.0 +ipython_genutils-0.2.0 +ipywidgets-7.4.1 +isort-4.3.4 +itsdangerous-0.24 +jbig-2.1 +jdcal-1.4 +jedi-0.12.1 +jeepney-0.3.1 +jinja2-2.10 +jpeg-9b +jsonschema-2.6.0 +jupyter-1.0.0 +jupyter_client-5.2.3 +jupyter_console-5.2.0 +jupyter_core-4.4.0 +jupyterlab-0.34.9 +jupyterlab_launcher-0.13.1 +keyring-13.2.1 +kiwisolver-1.0.1 +lazy-object-proxy-1.3.1 +libcurl-7.61.0 +libedit-3.1.20170329 +libffi-3.2.1 +libgcc-ng-8.2.0 +libgfortran-ng-7.3.0 +libpng-1.6.34 +libsodium-1.0.16 +libssh2-1.8.0 +libstdcxx-ng-8.2.0 +libtiff-4.0.9 +libtool-2.4.6 +libuuid-1.0.3 +libxcb-1.13 +libxml2-2.9.8 +libxslt-1.1.32 +llvmlite-0.24.0 +locket-0.2.0 +lxml-4.2.5 +lzo-2.10 +markupsafe-1.0 +matplotlib-2.2.3 +mccabe-0.6.1 +mistune-0.8.3 +mkl-2019.0 +mkl-service-1.1.2 +mkl_fft-1.0.4 +mkl_random-1.0.1 +more-itertools-4.3.0 +mpc-1.1.0 +mpfr-4.0.1 +mpmath-1.0.0 +msgpack-python-0.5.6 +multipledispatch-0.6.0 +navigator-updater-0.2.1 +nbconvert-5.4.0 +nbformat-4.4.0 +ncurses-6.1 +networkx-2.1 +nltk-3.3.0 +nose-1.3.7 +notebook-5.6.0 +numba-0.39.0 +numexpr-2.6.8 +numpy-1.15.1 +numpy-base-1.15.1 +numpydoc-0.8.0 +odo-0.5.1 +olefile-0.46 +openpyxl-2.5.6 +openssl-1.0.2p +packaging-17.1 +pandas-0.23.4 +pandoc-1.19.2.1 +pandocfilters-1.4.2 +pango-1.42.4 +parso-0.3.1 +partd-0.3.8 +patchelf-0.9 +path.py-11.1.0 +pathlib2-2.3.2 +patsy-0.5.0 +pcre-8.42 +pep8-1.7.1 +pexpect-4.6.0 +pickleshare-0.7.4 +pillow-5.2.0 +pip-10.0.1 +pixman-0.34.0 +pkginfo-1.4.2 +pluggy-0.7.1 +ply-3.11 +prometheus_client-0.3.1 +prompt_toolkit-1.0.15 +psutil-5.4.7 +ptyprocess-0.6.0 +py-1.6.0 +pyasn1-0.4.4 +pyasn1-modules-0.2.2 +pycodestyle-2.4.0 +pycosat-0.6.3 +pycparser-2.18 +pycrypto-2.6.1 +pycurl-7.43.0.2 +pyflakes-2.0.0 +pygments-2.2.0 +pylint-2.1.1 +pyodbc-4.0.24 +pyopenssl-18.0.0 +pyparsing-2.2.0 +pyqt-5.9.2 +pysocks-1.6.8 +pytables-3.4.4 +pytest-3.8.0 +pytest-arraydiff-0.2 +pytest-astropy-0.4.0 +pytest-doctestplus-0.1.3 +pytest-openfiles-0.3.0 +pytest-remotedata-0.3.0 +python-3.7.0 +python-dateutil-2.7.3 +pytz-2018.5 +pywavelets-1.0.0 +pyyaml-3.13 +pyzmq-17.1.2 +qt-5.9.6 +qtawesome-0.4.4 +qtconsole-4.4.1 +qtpy-1.5.0 +readline-7.0 +requests-2.19.1 +rope-0.11.0 +ruamel_yaml-0.15.46 +scikit-image-0.14.0 +scikit-learn-0.19.2 +scipy-1.1.0 +seaborn-0.9.0 +secretstorage-3.1.0 +send2trash-1.5.0 +service_identity-17.0.0 +setuptools-40.2.0 +simplegeneric-0.8.1 +singledispatch-3.4.0.3 +sip-4.19.8 +six-1.11.0 +snappy-1.1.7 +snowballstemmer-1.2.1 +sortedcollections-1.0.1 +sortedcontainers-2.0.5 +sphinx-1.7.9 +sphinxcontrib-1.0 +sphinxcontrib-websupport-1.1.0 +spyder-3.3.1 +spyder-kernels-0.2.6 +sqlalchemy-1.2.11 +sqlite-3.24.0 +statsmodels-0.9.0 +sympy-1.2 +tblib-1.3.2 +terminado-0.8.1 +testpath-0.3.1 +tk-8.6.8 +toolz-0.9.0 +tornado-5.1 +tqdm-4.26.0 +traitlets-4.3.2 +twisted-18.7.0 +unicodecsv-0.14.1 +unixodbc-2.3.7 +urllib3-1.23 +wcwidth-0.1.7 +webencodings-0.5.1 +werkzeug-0.14.1 +wheel-0.31.1 +widgetsnbextension-3.4.1 +wrapt-1.10.11 +xlrd-1.1.0 +xlsxwriter-1.1.0 +xlwt-1.3.0 +xz-5.2.4 +yaml-0.1.7 +zeromq-4.2.5 +zict-0.1.3 +zlib-1.2.11 +zope-1.0 +zope.interface-4.5.0 [scb3201@ln137%bscc-a6 ~]$ conda info active environment : base active env location : /public1/home/scb3201/anaconda3 shell level : 1 user config file : /public1/home/scb3201/.condarc populated config files : /public1/home/scb3201/.condarc conda version : 4.5.11 conda-build version : 3.15.1 python version : 3.7.0.final.0 base environment : /public1/home/scb3201/anaconda3 (writable) channel URLs : https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/linux-64 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/noarch https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/bioconda/linux-64 https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/bioconda/noarch https://repo.anaconda.com/pkgs/main/linux-64 https://repo.anaconda.com/pkgs/main/noarch https://repo.anaconda.com/pkgs/free/linux-64 https://repo.anaconda.com/pkgs/free/noarch https://repo.anaconda.com/pkgs/r/linux-64 https://repo.anaconda.com/pkgs/r/noarch https://repo.anaconda.com/pkgs/pro/linux-64 https://repo.anaconda.com/pkgs/pro/noarch package cache : /public1/home/scb3201/anaconda3/pkgs /public1/home/scb3201/.conda/pkgs envs directories : /public1/home/scb3201/anaconda3/envs /public1/home/scb3201/.conda/envs platform : linux-64 user-agent : conda/4.5.11 requests/2.19.1 CPython/3.7.0 Linux/3.10.0-1160.118.1.el7.x86_64 centos/7 glibc/2.17 UID:GID : 4238:4238 netrc file : None offline mode : False [scb3201@ln137%bscc-a6 ~]$ curl -v https://repo.anaconda.com/pkgs/r/linux-64/repodata.json.bz2 * Could not resolve host: repo.anaconda.com * Closing connection 0 curl: (6) Could not resolve host: repo.anaconda.com [scb3201@ln137%bscc-a6 ~]$ curl -I https://repo.anaconda.com/pkgs/r/linux-64/repodata.json.bz2 curl: (6) Could not resolve host: repo.anaconda.com [scb3201@ln137%bscc-a6 ~]$ echo $http_proxy # 检查代理变量 [scb3201@ln137%bscc-a6 ~]$ ping 8.8.8.8 # 测试基础网络连通性 PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
最新发布
11-24
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值