

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 在 Glue AWS 中使用 XML 格式
<a name="aws-glue-programming-etl-format-xml-home"></a>

AWS Glue 從來源擷取資料，並將資料寫入以各種資料格式存放和傳輸的目標。如果您的資料是以 XML 資料格式存放或傳輸，本文件會介紹在 Glue AWS 中使用資料的可用功能。

AWS Glue 支援使用 XML 格式。此格式表示並非基於資料列或資料行的、高度可設定且嚴格定義的資料結構。XML 是高度標準化的。如需標準授權單位的格式簡介，請參閱 [XML Essentials](https://www.w3.org/standards/xml/core) (XML 基礎知識)。

您可以使用 AWS Glue 從 Amazon S3 讀取 XML 檔案，以及包含 XML 檔案的 `bzip`和 `gzip`封存。您可以在 [S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3) 上設定壓縮行為，而不是在本頁討論的組態中設定。

下表顯示哪些常見的 AWS Glue 功能支援 XML 格式選項。


| 讀取 | 寫入 | 串流讀取 | 對小型檔案進行分組 | 任務書籤 | 
| --- | --- | --- | --- | --- | 
| 支援 | 不支援 | 不支援 | 支援 | 支援 | 

## 範例：從 S3 讀取 XML
<a name="aws-glue-programming-etl-format-xml-read"></a>

 XML 讀取器接受 XML 標籤名稱。它會檢查其輸入中包含該標籤的元素，以推斷結構描述，並使用對應的值填入 DynamicFrame。Glue XML AWS 功能的行為類似於 [Apache Spark 的 XML 資料來源](https://github.com/databricks/spark-xml)。您可以透過比較此讀取器與該專案的文件，來獲得基本行為相關的洞見。

**先決條件：**您需要指向希望讀取的 XML 檔案或資料夾的 S3 路徑 (`s3path`) 以及有关 XML 檔案的部分資訊。您還需要希望讀取的 XML 元素的標籤，`xmlTag`。

 **組態：**在您的函數選項中，指定 `format="xml"`。在您的 `connection_options` 中，使用 `paths` 鍵來指定 `s3path`。您可以在 `connection_options` 中进一步設定讀取器與 S3 的互動方式。如需詳細資訊，請參閱 Glue 中 ETL AWS 的連線類型和選項：[S3 連線參數](aws-glue-programming-etl-connect-s3-home.md#aws-glue-programming-etl-connect-s3)。在您的 `format_options` 中，使用 `rowTag` 鍵來指定 `xmlTag`。您可以在 `format_options` 中进一步設定讀取器解譯 XML 檔案的方式。如需詳細資訊，請參閱 [XML 組態參考](#aws-glue-programming-etl-format-xml-reference)。

以下 AWS Glue ETL 指令碼顯示從 S3 讀取 XML 檔案或資料夾的流程。

------
#### [ Python ]

在此範例中，使用 [create\$1dynamic\$1frame.from\$1options](aws-glue-api-crawler-pyspark-extensions-glue-context.md#aws-glue-api-crawler-pyspark-extensions-glue-context-create_dynamic_frame_from_options) 方法。

```
# Example: Read XML from S3
# Set the rowTag option to configure the reader.

from awsglue.context import GlueContext
from pyspark.context import SparkContext

sc = SparkContext.getOrCreate()
glueContext = GlueContext(sc)

dynamicFrame = glueContext.create_dynamic_frame.from_options(
    connection_type="s3",
    connection_options={"paths": ["s3://s3path"]},
    format="xml",
    format_options={"rowTag": "xmlTag"},
)
```

您也可以在指令碼中使用 DataFrames (`pyspark.sql.DataFrame`)。

```
dataFrame = spark.read\
    .format("xml")\
    .option("rowTag", "xmlTag")\
    .load("s3://s3path")
```

------
#### [ Scala ]

在此範例中，使用 [getSourceWithFormat](glue-etl-scala-apis-glue-gluecontext.md#glue-etl-scala-apis-glue-gluecontext-defs-getSourceWithFormat) 操作。

```
// Example: Read XML from S3
// Set the rowTag option to configure the reader.

import com.amazonaws.services.glue.util.JsonOptions
import com.amazonaws.services.glue.GlueContext
import org.apache.spark.sql.SparkSession

val glueContext = new GlueContext(SparkContext.getOrCreate())
val sparkSession: SparkSession = glueContext.getSparkSession

object GlueApp {
  def main(sysArgs: Array[String]): Unit = {
    val dynamicFrame = glueContext.getSourceWithFormat(
      formatOptions=JsonOptions("""{"rowTag": "xmlTag"}"""), 
      connectionType="s3", 
      format="xml", 
      options=JsonOptions("""{"paths": ["s3://s3path"], "recurse": true}""")
    ).getDynamicFrame()
}
```

您也可以在指令碼中使用 DataFrames (`org.apache.spark.sql.DataFrame`)。

```
val dataFrame = spark.read
  .option("rowTag", "xmlTag")
  .format("xml")
  .load("s3://s3path“)
```

------

## XML 組態參考
<a name="aws-glue-programming-etl-format-xml-reference"></a>

只要 Glue AWS 程式庫指定 `format_options`，您就可以使用下列項目`format="xml"`：
+ `rowTag` – 指定要將其當做一列的檔案中的 XML 標籤。Row 標籤不能自動關閉。
  + **類型：**文字，**必要**
+ `encoding` – 指定字元編碼。它可以是我们的執行時間環境支援的 [Charset](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html) 名稱或別名。我們不對編碼支援做出具體保證，但主要編碼應可適用。
  + **類型：**文字，**預設：**`"UTF-8"`
+ `excludeAttribute` – 指定是否要排除元素中的屬性。
  + **類型：**布林值，**預設：**`false`
+ `treatEmptyValuesAsNulls` – 指定是否要將空格當做 null 值。
  + **類型：**布林值，**預設：**`false`
+ `attributePrefix` – 屬性的字首，用以和子元素文字作區別。此前綴用於欄位名稱。
  + **類型：**文字，**預設：**`"_"`
+ `valueTag` – 當無子元素的元素有屬性時，此標籤會當做一個值。
  + **類型：**文字，**預設：**`"_VALUE"`
+ `ignoreSurroundingSpaces` – 指定是否要忽略前後均有值的空格。
  + **類型：**布林值，**預設：**`false`
+ `withSchema` – 如果要覆寫推斷的結構描述，则包含預期的結構描述。若不使用此選項，AWS Glue 會從 XML 資料推斷出結構描述。
  + **類型：**文字，**預設：**不適用
  + 此值應為代表 `StructType` 的 JSON 物件。

## 手動指定 XML 結構描述
<a name="aws-glue-programming-etl-format-xml-withschema"></a>

**手動 XML 結構描述範例**

這是使用 `withSchema` 格式選項來指定 XML 資料結構描述的範例。

```
from awsglue.gluetypes import *

schema = StructType([ 
  Field("id", IntegerType()),
  Field("name", StringType()),
  Field("nested", StructType([
    Field("x", IntegerType()),
    Field("y", StringType()),
    Field("z", ChoiceType([IntegerType(), StringType()]))
  ]))
])

datasource0 = create_dynamic_frame_from_options(
    connection_type, 
    connection_options={"paths": ["s3://xml_bucket/someprefix"]},
    format="xml", 
    format_options={"withSchema": json.dumps(schema.jsonValue())},
    transformation_ctx = ""
)
```