xml解析方案
有一个比较复杂的Xml,有很多循环嵌套,如何将其中需要的元素拿出来呢?
1、Java类库解析
Java中有许多第三方库可以解析xml.
<!--使用Dom的方式解析xml-->
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>2.0.2</version>
</dependency>
<!--使用反射将xml和JavaBean对应-->
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.11.1</version>
</dependency>
<!--jackson中解析xml的库,和json用法一样,可以用在Spring中-->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.8</version>
</dependency>
使用dom4jjdom解析xml的时候,就是在处理dom模型,处理Node,Element.
使用xstream这种类库,可以和Java实体类做映射。
处理Xml
刚开始,由于xml内容实在太多,我将其和JavaBean做映射,先通过xml获取实体类,然后映射。
不过由于xml中有循环节点,如下,然后里面被嵌套的部分无法映射,然后我把无法映射的字符串抽离出来,单独映射再拼接到实体对象中,还算可以,不过其实里面有很多属性是我用不上的。
优点:简单直接,只需要得到映射实体类即可。
缺点:需要对重要属性做映射,这个过程可能比较烦。
<struct> <body> <struct> <body> <struct>结构嵌套</struct> </body> </struct> <struct></struct> <struct></struct> </body> </struct>
使用Dom4j解析xml缺点就是如果需要解析出的元素比较多,那可能工程量比较大。
如果只取部分元素,还是挺好用的。
2、Spark解析
Spark可以读写数据,读xml文件导入这个库即可。
解析xml如果没有指定schema,那么需要指定一个根标签,此时会自动推断出xml结构。
<dependency>
<groupId>com.databricks</groupId>
<artifactId>spark-xml_2.12</artifactId>
<version>0.11.0</version>
</dependency>
如这样:
val frame: DataFrame = spark.read.format("com.databricks.spark.xml")
.option("rowTag", "structuredBody")
.load("xxx")
frame.printSchema
//结构大概如此
root
|-- component: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- section: struct (nullable = true)
| | | |-- code: struct (nullable = true)
| | | | |-- _VALUE: string (nullable = true)
| | | | |-- _code: string (nullable = true)