我有以下 xml 文档
<a date="26-03-2018" id="1">
<text>
</text>
<metadata>
<b>
<c c="STRING1">
<d="value" e="string"/>
</c>
<c c="STRING2">
<d="value2" e="string" />
</c>
</b>
</metadata>
</a>
通过使用数据砖 xml 解析器,我想提取 string1
, string2
c
的值作为 column[metadata]
的列表数据框,但是当我用自定义模式推断时schema = StructType([
StructField("date", StringType(), True),
StructField("id", LongType(), True),
StructField("text", StringType(), True),
StructField("metadata", StructType([
StructField("b", StringType(), True)]), True),])
以及上述模式的数据框----------------------------------------------------------------------------------------------------------------------
Id | date | text | metadata
----------------------------------------------------------------------------------------------------------------------
1 | 26-03-2018 | text |' <c c="STRING1"> <d="value" e="string"/></c><c c="STRING2"><d="value2" e="string" /> </c>'
我从 b
获取整个数据作为字符串节点。关于如何使用 databricks xml 解析器仅将字符串提取到名为元数据的列的任何想法,或者是否有任何其他可用的解析器。我找不到正确的解决方案。
最佳答案
您可以使用 rdd 来解析和 ElementTree 库。
from pyspark.sql import Row
import xml.etree.ElementTree as ET
row_counter = Row('columnName1', 'columnName2', 'columnName3')
def parser_xml(string_xml):
root = ET.fromstring(string_xml.encode('ISO-8859-1', errors='replace'))
''' Implement all parser logic
'''
columnName1 = root.find('test').attrib['value1']
columnName2 = root.find('test2').attrib['value2']
columnName3 = root.find('test3').attrib['value3']
return row_counter(columnName1, columnName2, columnName3)
rdd = sc.wholeTextFiles("/files/*.xml")
data = rdd.map(lambda (string_file): parser_xml(string_file[1]))
df = spark.createDataFrame(data, schema=None, samplingRatio=None, verifySchema=True)
df.write.parquet('output')
关于python - 如何在pyspark中解析嵌套的xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49494111/