如何处理SOAP with Attachments中的XML映射

10次阅读

SOAP with Attachments 的 xml 映射本质是分离式解析:先解包 MIME multipart,再解析 SOAP XML,最后按 xop:includehref 引用的 CID 手动绑定附件;JAXB/Jackson 无法直接反序列化,须用 SOAPMessage(java)或 email 模块(python)解析。

如何处理SOAP with Attachments中的XML映射

SOAP with Attachments 的 XML 映射本质是分离式解析

SOAP with Attachments(SwA)不是把附件塞进 XML,而是用 MIME multipart 封装一个 SOAP Envelope 和若干二进制/文本附件。XML 本身不包含附件内容,只可能通过 xop:Includehref 引用 CID(Content-ID)。所以“XML 映射”实际是:先拆解 MIME,再解析主 XML,最后按引用关系绑定附件。硬套 JAXB 或 Jackson 直接反序列化会失败——它们看不到 MIME 边界。

Java 中用 javax.xml.soap.SOAPMessage 解析 SwA 最可靠

这是 JAX-WS 底层原生支持 SwA 的方式,能自动识别 multipart/related 并分离出 SOappartAttachmentPart。关键点:

  • SOAPMessage 必须从 Inputstream 构建(不能从字符串dom),否则 MIME 头丢失
  • 附件的 Content-ID 格式必须为 ,且 XML 中的 href 值需严格匹配(含尖括号)
  • 调用 getAttachments() 后,需手动遍历并用 getContentId() 关联 XML 中的 xop:Includehref
SOAPMessage message = MessageFactory.newinstance().createMessage(null, inputStream); SOAPPart soapPart = message.getSOAPPart(); Document doc = soapPart.getEnvelope().getOwnerDocument(); // 获取 XML DOM Iterator it = message.getAttachments(); while (it.hasNext()) {     AttachmentPart ap = it.next();     String cid = ap.getContentId(); // 如 ""     // 手动查找 doc 中 href="cid:image.jpg@soap.example" 的节点并注入数据 }

Python 没有标准 SwA 支持,得靠 email 模块手撕 MIME

requestsurllib 返回的响应体是原始 bytes,必须用 email.parser.BytesParser 解析 multipart。常见陷阱:

  • MIME boundary 在 http Content-Type 头里,但 BytesParser 需要完整头+body,不能只传 body
  • SOAP 主体的 Content-Type 必须是 text/xmlapplication/soap+xml,否则会被当普通 part
  • 附件的 Content-ID 可能被邮件库标准化为无尖括号形式,而 XML 中仍带 ,比对前需统一格式
from email.parser import BytesParser from email.policy import default 

response.content 是完整的 HTTP 响应体(含 headers + body)

msg = BytesParser(policy=default).parsebytes(response.content) for part in msg.iter_parts(): content_type = part.get_content_type() content_id = part.get("Content-ID", "").strip("<>") if content_type == "text/xml": xml_bytes = part.get_content() elif content_id and part.get_payload(decode=True): attachment_data = part.get_payload(decode=True)

手动映射到 xml 中的 xop:Include href="cid:{content_id}"

}

XML 中的 xop:Include 不是自动解析的占位符

即使你用 JAXB 或 lxml 加载了主 XML, 仍只是普通元素,不会自动替换成附件数据。必须自己做两件事:

  • 在解析 XML 后,遍历所有 xop:Include 节点,提取 href 值并标准化为 CID 键
  • 查附件映射表(从 MIME 解析阶段构建),把对应二进制数据注入到父节点、或替换为 base64 字符串、或存为独立文件路径
  • 注意命名空间xop 前缀必须声明为 http://www.w3.org/2004/08/xop/include,否则 XPath 查不到

最易忽略的是:SwA 规范允许附件用 Content-Transfer-Encoding: binary,但某些老客户端发的是 base64。解析时得看 header,不能默认 decode。

text=ZqhQzanResources