I have a spark session opened and a directory with a .xml file on it. I just want to read the schema of the .xml file but I guess spark doesn´t do it directly as if, for example, I want to read a parquet.
I mean, I´m trying to do something like:
path = "/.../.../.../filename.xml"
df_xml = spark.read.format("xml").option("rowTag", "<the rowTag name here>").load(path)
df_xml.printSchema()
What I got is:
File "/opt/mapr/spark/spark-2.4.4/python/pyspark/sql/readwriter.py", line 166, in load
return self._df(self._jreader.load(path))
File "/opt/mapr/spark/spark-2.4.4/python/lib/py4j-0.10.7-src.zip/py4j/java_gateway.py", line 1257, in __call__
File "/opt/mapr/spark/spark-2.4.4/python/pyspark/sql/utils.py", line 63, in deco
return f(*a, **kw)
File "/opt/mapr/spark/spark-2.4.4/python/lib/py4j-0.10.7-src.zip/py4j/protocol.py", line 328, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o92.load.
: java.lang.ClassNotFoundException: Failed to find data source: xml.
Caused by: java.lang.ClassNotFoundException: xml.DefaultSource
Has anyone try to read the schema of a xml file in pyspark? I´m new on this, I´ll really appreciate your feedback.
CodePudding user response:
Parquet format contains information about the schema, XML doesn't. You can't just read the schema without inferring it from the data.
Since I don't have information about your XML file I'll use this sample: XML Sample File
Save that XML sample to sample.xml
and you'll have to specify the Spark XML package in order to parse the XML file.
Here's the example:
from pyspark.sql import SparkSession
if __name__ == "__main__":
spark = SparkSession \
.builder \
.appName("Test") \
.config("spark.jars.packages", "com.databricks:spark-xml_2.12:0.13.0") \
.getOrCreate()
df = spark.read.format('xml').options(rowTag='catalog').load('sample.xml')
df.printSchema()
The result is:
root
|-- book: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- _id: string (nullable = true)
| | |-- author: string (nullable = true)
| | |-- description: string (nullable = true)
| | |-- genre: string (nullable = true)
| | |-- price: double (nullable = true)
| | |-- publish_date: date (nullable = true)
| | |-- title: string (nullable = true)