如何使用jQuery解析SOAP请求返回的XML数据
Got it, let's work through this SOAP XML problem you're stuck on. Since you can't rely on node counts or positions to track down the node with the value result, XPath is your go-to tool—it lets you target nodes based on their content or name directly, no matter where they live in the XML structure.
Key Consideration: SOAP Namespaces
First, SOAP XML always uses namespaces (like the soapenv one in your snippet), so we need to handle those in our XPath queries to avoid missing nodes.
Example 1: Find Nodes Whose Text Content is result
If you're looking for any node whose text exactly matches result (ignoring extra whitespace), here's how to do it in Python with xml.etree.ElementTree:
import xml.etree.ElementTree as ET # Replace this with your full SOAP XML content soap_xml = """<?xml version="1.0" encoding="utf-8"?> <soapenv:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Body> <SampleResponse> <status>success</status> <output>result</output> </SampleResponse> </soapenv:Body> </soapenv:Envelope> """ # Map the namespaces from your XML to short prefixes namespaces = { 'soapenv': 'http://schemas.xmlsoap.org/soap/envelope/', # Add any other namespaces used in your actual XML (like your service's namespace) } # Parse the XML root = ET.fromstring(soap_xml) # XPath to find nodes where text (stripped of whitespace) equals "result" target_nodes = root.findall("//*[normalize-space(text())='result']", namespaces=namespaces) # Extract the text from each matching node for node in target_nodes: print("Found result text:", node.text.strip())
Example 2: Find Nodes Named result (Regardless of Position)
If you actually need nodes with the name result (and want to get their text content), use this XPath instead. This ignores the node's position entirely:
# XPath to find any node named "result" (using local-name() to bypass namespace if needed) target_nodes = root.findall("//*[local-name()='result']", namespaces=namespaces) for node in target_nodes: print("Result node text:", node.text.strip())
Why This Works
//*searches the entire XML tree (not just direct children), so it doesn't matter where the node is located.normalize-space()handles any extra spaces/newlines in the node text, so you don't miss matches due to whitespace.- Using namespaces ensures you don't skip nodes that are part of the SOAP envelope or your service's namespace.
内容的提问来源于stack exchange,提问作者Dirty Bird Design

