HTTP XML
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
剖析包含「application/xml」內容的 HTTP 要求。
程式碼範例
Java
如要驗證 Cloud Run 函式,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
Node.js
如要驗證 Cloud Run 函式,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
Python
如要驗證 Cloud Run 函式,請設定應用程式預設憑證。
詳情請參閱「為本機開發環境設定驗證」。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis page demonstrates how to parse HTTP requests containing "application/xml" content using various programming languages.\u003c/p\u003e\n"],["\u003cp\u003eThe provided code samples showcase how to handle and process XML data within HTTP requests in Go, Java, Node.js, and Python.\u003c/p\u003e\n"],["\u003cp\u003eEach language-specific example offers a distinct approach to parsing XML, using built in libraries or installing external ones.\u003c/p\u003e\n"],["\u003cp\u003eAuthentication for Cloud Run functions, requires setting up Application Default Credentials, according to the resources.\u003c/p\u003e\n"],["\u003cp\u003eThe page also suggests exploring the Google Cloud sample browser to find additional code samples for different Google Cloud products.\u003c/p\u003e\n"]]],[],null,["# HTTP XML\n\nParses an HTTP request that contains \"application/xml\" content.\n\nCode sample\n-----------\n\n### Go\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // Package http provides a set of HTTP Cloud Functions samples.\n package http\n\n import (\n \t\"encoding/xml\"\n \t\"fmt\"\n \t\"html\"\n \t\"io\"\n \t\"net/http\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n )\n\n func init() {\n \tfunctions.HTTP(\"ParseXML\", ParseXML)\n }\n\n // ParseXML is an example of parsing a text/xml request.\n func ParseXML(w http.ResponseWriter, r *http.Request) {\n \tvar d struct {\n \t\tName string\n \t}\n \tb, err := io.ReadAll(r.Body)\n \tif err != nil {\n \t\thttp.Error(w, \"Could not read request\", http.StatusBadRequest)\n \t}\n \tif err := xml.Unmarshal(b, &d); err != nil {\n \t\thttp.Error(w, \"Could not parse request\", http.StatusBadRequest)\n \t}\n \tif d.Name == \"\" {\n \t\td.Name = \"World\"\n \t}\n \tfmt.Fprintf(w, \"Hello, %v!\", html.EscapeString(d.Name))\n }\n\n### Java\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import com.google.cloud.functions.HttpFunction;\n import com.google.cloud.functions.HttpRequest;\n import com.google.cloud.functions.HttpResponse;\n import java.io.ByteArrayInputStream;\n import java.io.IOException;\n import java.io.InputStream;\n import java.io.PrintWriter;\n import java.net.HttpURLConnection;\n import javax.xml.parsers.DocumentBuilder;\n import javax.xml.parsers.DocumentBuilderFactory;\n import javax.xml.parsers.ParserConfigurationException;\n import org.w3c.dom.Document;\n import org.xml.sax.SAXException;\n\n public class ParseXml implements HttpFunction {\n private static DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n\n // Parses a HTTP request in XML format\n // (Responds with a 400 error if the HTTP request isn't valid XML.)\n @Override\n public void service(HttpRequest request, HttpResponse response)\n throws IOException, ParserConfigurationException {\n\n try {\n DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();\n var writer = new PrintWriter(response.getWriter());\n\n // Get request body\n InputStream bodyStream = new ByteArrayInputStream(\n request.getInputStream().readAllBytes());\n\n // Parse + process XML\n Document doc = docBuilder.parse(bodyStream);\n writer.printf(\"Root element: %s\", doc.getDocumentElement().getNodeName());\n } catch (SAXException e) {\n response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST);\n return;\n }\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n const functions = require('@google-cloud/functions-framework');\n\n /**\n * Parses a document of type 'text/xml'\n *\n * @param {Object} req Cloud Function request context.\n * @param {Object} res Cloud Function response context.\n */\n functions.http('parseXML', (req, res) =\u003e {\n // Convert the request to a Buffer and a string\n // Use whichever one is accepted by your XML parser\n const data = req.rawBody;\n const xmlData = data.toString();\n\n const {parseString} = require('xml2js');\n\n parseString(xmlData, (err, result) =\u003e {\n if (err) {\n console.error(err);\n res.status(500).end();\n return;\n }\n res.send(result);\n });\n });\n\n### Python\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import json\n\n import functions_framework\n\n import xmltodict\n\n @functions_framework.http\n def parse_xml(request):\n \"\"\"Parses a document of type 'text/xml'\n Args:\n request (flask.Request): The request object.\n Returns:\n The response text, or any set of values that can be turned into a\n Response object using `make_response`\n \u003chttp://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response\u003e.\n \"\"\"\n data = xmltodict.parse(request.data)\n return json.dumps(data, indent=2)\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]