使用 spark 解析具有多个行标签的 xml

parse xml with multiple rowtags using spark

我想使用 spark 解析器 xml,所以我使用的是 spark databricks 库。样本xml如下:

<Transactions>
        <Transaction>                
                <transid>1111</transid>                
        </Transaction>  
        <Transaction>                
                <transid>2222</transid>                
        </Transaction>      
</Transactions>
<Payments>
    <Payment>
        <Id>123</Id>
    </Payment>
    <Payment>
        <Id>456</Id>
    </Payment>
</Payments>

要解析的代码:

val transNestedDF = sqlContext.read.format("com.databricks.spark.xml").option("rowTag","Transactions").load("trans_nested.xml")

transNestedDF.registerTempTable("TransNestedTbl")

sqlContext.sql("select Transaction[0].transid from TransNestedTbl").collect()

这里我没有任何根标签,我也不能定义多行标签,所以如果我必须使用上面的单个数据帧在单次读取中处理交易和支付,那么如何实现呢?

需要帮助。

让我们尝试使用 lxml,一个 python 库,它本身使用 xpath:

如果您没有安装它,您需要:

pip intall lxml

然后:

import lxml.html

pay = """ [your code above]  """

doc = lxml.html.fromstring(pay)
tid =doc.xpath('Transactions//transid'.lower()) #or ('//Transactions//transid'.lower()) depending on the structure of the original doc
pid = doc.xpath('Payments//id'.lower()) #same comment

final = ''
for i in tid:
    for p in pid:            
        final = final+i.text+'|'+p.text+' \n'

print(final)

输出:

1111|123 
1111|456 
2222|123 
2222|456 

如果这两个都没有标签,你不能一口气读完。如果有任何共同的父标记,您可以将其用作 rowTag 并忽略解析的其余部分。

你当然可以将它们分别读入两个DataFrame。如果您分别对待它们,那效果很好。但是你失去了交易和支付之间的关联,除非你可以加入一些ID。

但后来我想知道为什么 XML 结构没有 any 共同的父级,如果它们是关联的。