首页 > 解决方案 > 在 Spark 中读取 XML

问题描述

我正在尝试使用 spark-xml jar 在 pyspark 中读取 xml/嵌套 xml。

df = sqlContext.read \
  .format("com.databricks.spark.xml")\
   .option("rowTag", "hierachy")\
   .load("test.xml"

当我执行时,数据框没有正确创建。

    +--------------------+
    |                 att|
    +--------------------+
    |[[1,Data,[Wrapped...|
    +--------------------+

下面提到了我拥有的 xml 格式:

在此处输入图像描述

标签: xmlapache-sparkdataframepysparkapache-spark-xml

解决方案


heirarchy应该是rootTag并且att应该是rowTag

df = spark.read \
    .format("com.databricks.spark.xml") \
    .option("rootTag", "hierarchy") \
    .option("rowTag", "att") \
    .load("test.xml")

你应该得到

+-----+------+----------------------------+
|Order|attval|children                    |
+-----+------+----------------------------+
|1    |Data  |[[[1, Studyval], [2, Site]]]|
|2    |Info  |[[[1, age], [2, gender]]]   |
+-----+------+----------------------------+

schema

root
 |-- Order: long (nullable = true)
 |-- attval: string (nullable = true)
 |-- children: struct (nullable = true)
 |    |-- att: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- Order: long (nullable = true)
 |    |    |    |-- attval: string (nullable = true)

查找有关databricks xml的更多信息


推荐阅读