XML HTTP
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Menguraikan permintaan HTTP yang berisi konten "application/xml".
Contoh kode
Kecuali dinyatakan lain, konten di halaman ini dilisensikan berdasarkan Lisensi Creative Commons Attribution 4.0, sedangkan contoh kode dilisensikan berdasarkan Lisensi Apache 2.0. Untuk mengetahui informasi selengkapnya, lihat Kebijakan Situs Google Developers. Java adalah merek dagang terdaftar dari Oracle dan/atau afiliasinya.
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","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)."]]