下面是我的数据框。
+-------+----+----------+ | city|year|saleAmount| +-------+----+----------+ |Toronto|2017| 50.0| |Toronto|null| 50.0| |Sanjose|2017| 200.0| |Sanjose|null| 200.0| | Plano|2015| 50.0| | Plano|2016| 50.0| | Plano|null| 100.0| |Newyork|2016| 150.0| |Newyork|null| 150.0| | Dallas|2016| 100.0| | Dallas|2017| 120.0| | Dallas|null| 220.0| | null|null| 720.0| +-------+----+----------+
I tried to convert that to xml using
df.write.format("com.databricks.spark.xml")
.mode("overwrite")
.option("treatEmptyValuesAsNulls", "true")
.option("rowTag", "ROW")
.save("myxml")
但是 xml 中缺少一些标签,如下所示
<ROWS>
<ROW>
<city>Toronto</city>
<year>2017</year>
<saleAmount>50.0</saleAmount>
</ROW>
<ROW>
<city>Toronto</city>
<saleAmount>50.0</saleAmount>
</ROW>
<ROW>
<city>Sanjose</city>
<year>2017</year>
<saleAmount>200.0</saleAmount>
</ROW>
<ROW>
<city>Sanjose</city>
<saleAmount>200.0</saleAmount>
</ROW>
<ROW>
<city>Plano</city>
<year>2015</year>
<saleAmount>50.0</saleAmount>
</ROW>
<ROW>
<city>Plano</city>
<year>2016</year>
<saleAmount>50.0</saleAmount>
</ROW>
<ROW>
<city>Plano</city>
<saleAmount>100.0</saleAmount>
</ROW>
<ROW>
<city>Newyork</city>
<year>2016</year>
<saleAmount>150.0</saleAmount>
</ROW>
<ROW>
<city>Newyork</city>
<saleAmount>150.0</saleAmount>
</ROW>
<ROW>
<city>Dallas</city>
<year>2016</year>
<saleAmount>100.0</saleAmount>
</ROW>
<ROW>
<city>Dallas</city>
<year>2017</year>
<saleAmount>120.0</saleAmount>
</ROW>
<ROW>
<city>Dallas</city>
<saleAmount>220.0</saleAmount>
</ROW>
<ROW>
<saleAmount>720.0</saleAmount>
</ROW>
</ROWS>
打印时的 DataFrame,如上所示,它正确给出了所有空值。但是当转换为 XML 时,相应的 xml 元素标签丢失了...这是 databrics XML api 的工作方式吗?
在上面的 xml 中缺少 year
...因为数据框中的 year
值为 null
。
spark-xml中有没有选项其中还显示 null
值标签?
最佳答案
如果你想输出空标签,你需要提供一个默认的nullValue
,它将出现在标签中:
df.write.format("xml")
.mode("overwrite")
.option("nullValue", "")
.option("rowTag", "ROW")
.save("myxml")
将会产生
<ROWS>
<ROW>
<city>Toronto</city>
<year>2017</year>
<saleAmount>50.0</saleAmount>
</ROW>
<ROW>
<city>Toronto</city>
<year></year>
<saleAmount>50.0</saleAmount>
</ROW>
<ROW>
<city>Sanjose</city>
<year>2017</year>
<saleAmount>200.0</saleAmount>
</ROW>
<ROW>
<city>Sanjose</city>
<year></year>
<saleAmount>200.0</saleAmount>
</ROW>
<ROW>
<city>Plano</city>
<year>2015</year>
<saleAmount>50.0</saleAmount>
</ROW>
...
</ROWS>
现在这可能是一个非常糟糕的主意,因为您无法为每个标签指定不同的值,因此很容易生成不符合其应符合的任何 XSD 的 xml 文件。
在上面的示例中,要读取生成的文件,您需要将 treatEmptyValuesAsNulls
选项设置为 true 或指定 nullValue
选项:
val df = spark.read.format("xml").option("treatEmptyValuesAsNulls","true").load("myxml")
or
val df = spark.read.format("xml").option("nullValue","").load("myxml")
关于xml - 当空值出现时 Spark XML 标签丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57810921/