格式化和验证Hadoop,Spark等xml配置文件的工具xmllint

来源:互联网 发布:解数独算法 编辑:程序博客网 时间:2024/06/09 23:48
从事Hadoop,HBase,Spark等大数据相关工作的朋友都知道,我们部署大数据平台时,经常会配置xml文件,但是往往配置的参数比较乱,而且有可能格式也会配置错误,所以希望能有一个工具能够帮助我们对于xml文件进行格式化和验证正确性。
xmllint便是一个很方便的处理及验证xml的工具,linux下只要安装libxml2就可以使用这个命令,而且一般Linux默认已经部署libxml2了。


查看安装包名称:
$ rpm -qa | grep libxml2
libxml2-2.7.6-20.el6.x86_64
libxml2-python-2.7.6-20.el6.x86_64


查看安装包部署的所有文件,其中便包含了xmllint工具:
$ rpm -ql libxml2-2.7.6-20.el6.x86_64
/usr/bin/xmlcatalog
/usr/bin/xmllint
/usr/lib64/libxml2.so.2
/usr/lib64/libxml2.so.2.7.6
/usr/share/doc/libxml2-2.7.6
/usr/share/doc/libxml2-2.7.6/AUTHORS
/usr/share/doc/libxml2-2.7.6/ChangeLog.gz
/usr/share/doc/libxml2-2.7.6/Copyright
/usr/share/doc/libxml2-2.7.6/NEWS
/usr/share/doc/libxml2-2.7.6/README
/usr/share/doc/libxml2-2.7.6/TODO
/usr/share/man/man1/xmlcatalog.1.gz
/usr/share/man/man1/xmllint.1.gz
/usr/share/man/man3/libxml.3.gz




这里,我们只会介绍xmllint的两个命令,其他功能自己可以通过man查看帮助文档。




1. --format 
格式化xml,使其具有良好的可读性。


演示文件内容如下,格式比较乱:
$ cat hbase-site_sample.xml 
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>


<configuration>
<property>
  <name>hbase.rootdir</name>
<value>hdfs://SZB-L0023776:8020/hbase114</value>
     </property>
  
  <property><name>hbase.client.write.buffer</name><value>2097152</value>
  </property>
</configuration>  


执行格式化操作:
$ xmllint --format  hbase-site_sample.xml


输出结果:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
  <property>
    <name>hbase.rootdir</name>
    <value>hdfs://SZB-L0023776:8020/hbase114</value>
  </property>
  <property>
    <name>hbase.client.write.buffer</name>
    <value>2097152</value>
  </property>
</configuration>


可以看到输出的格式比较整齐,方便阅读。


2. --noout
验证xml文件并打印验证的结果。
其实如果xml语法有错误时,--format参数也是能够检查出来的。


演示文件内容如下,格式有错误,最后多了一个<property>:
$ cat hbase-site_sample.xml 
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>


<configuration>
<property>
  <name>hbase.rootdir</name>
<value>hdfs://SZB-L0023776:8020/hbase114</value>
     </property>
  
  <property><name>hbase.client.write.buffer</name><value>2097152</value>
  </property>
  <property>
</configuration>  


执行检查操作:
$ xmllint --noout hbase-site_sample.xml 
hbase-site_sample.xml:13: parser error : Opening and ending tag mismatch: property line 12 and configuration
</configuration>  
                ^
hbase-site_sample.xml:14: parser error : Premature end of data in tag configuration line 4


^
可以看到有错误,我们将测试文档中多余的<property>去掉再验证一次:
$ xmllint --noout hbase-site_sample.xml
没有输出说明没有问题。


0 0
原创粉丝点击