gpt4 book ai didi

scala - 使用 DataFrame 解析混合内容 XML

转载 作者:行者123 更新时间:2023-12-03 14:57:40 24 4
gpt4 key购买 nike

我有一个包含混合内容的 XML 文档,我在 Dataframe 中使用自定义架构来解析它。我遇到了一个问题,即架构只会选择“测量”的文本。

XML 看起来像这样

<QData>
<Measure> some text here
<Answer>Answer1</Answer>
<Question>Question1</Question>
</Measure>
<Measure> some text here
<Answer>Answer1</Answer>
<Question>Question1</Question>
</Meaure>
</QData>

我的架构如下:
def getCustomSchema():StructType = {StructField("QData",
StructType(Array(
StructField("Measure",
StructType( Array(
StructField("Answer",StringType,true),
StructField("Question",StringType,true)
)),true)
)),true)}

当我尝试访问 Measure 中的数据时,我只收到“这里有一些文本”,当我尝试从 Answer 获取信息时失败。我也只是得到一个措施。

编辑:这就是我试图访问数据的方式
val result = sc.read.format("com.databricks.spark.xml").option("attributePrefix", "attr_").schema(getCustomSchema)
.load(filename.toString)

val qDfTemp = result.mapPartitions(partition =>{val mapper = new QDMapper();partition.map(row=>{mapper(row)}).flatMap(list=>list)}).toDF()

case class QDMapper(){
def apply(row: Row):List[QData]={
val qDList = new ListBuffer[QData]()
val qualData = row.getAs[Row]("QData") //When I print as list I get the first Measure text and that is it
val measure = qualData.getAs[Row]("Measure") //This fails
}
}

最佳答案

您可以使用行标记作为根标记并访问其他元素:-

df_schema = sqlContext.read.format('com.databricks.spark.xml').options(rowTag='<xml_tag_name>').load(schema_path)
请访问 https://github.com/harshaltaware/Pyspark/blob/main/Spark-data-parsing/xmlparsing.py对于简短的代码

关于scala - 使用 DataFrame 解析混合内容 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48063362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com