首页 > 解决方案 > 从 javascript 中的 javascript 方法解析 xml 输出

问题描述

我对 xml 和 javascript 很陌生。我在js中编写了一个方法,当通过soapUI调用时,它以以下格式返回输出。我试图从 javascript 调用相同的函数。如何解析输出?

我尝试了下面的代码,但没有奏效。

var tmp = interactionProposeOffers(offerEnvironment + "|" + offerSpace, recipientId, 1, xml, 0 , "", "" , "" , "" , "" , true);
var res = new XML(tmp.toXMLString());

肥皂反应:

<SOAP-ENV:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns="http://xml.apache.org/xml-soap" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Body>
      <urn:ProposeResponse xmlns:urn="urn:nms:interaction">
         <interactionId xsi:type="xsd:string">0</interactionId>
         <propositions xsi:type="ns:Element" SOAP-ENV:encodingStyle="http://xml.apache.org/xml-soap/literalxml">
            <propositions>
               <proposition id="43030" offer-id="11074076" offerSpace-id="7652687" weight="1" rank="1" prodOffer="">
                  <view>
                     <messageId>123</messageId>
                     <messageType>ABC</messageType>
                  </view>
               </proposition>
            </propositions>
         </propositions>
         <uuid/>
      </urn:ProposeResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

标签: javascriptmethodssoapui

解决方案


首先,现代 API 通常以 Accept 标头中设置的格式返回输出,因此如果将其设置为 application/json,则可能会以易于使用的格式(JavaScript Object Notation = json)获得输出。

如果这不是一个选项,您可以尝试使用 DOMParser ( https://www.w3schools.com/xml/xml_parser.asp ),尽管它感觉很难使用。一种开箱即用的解决方案是使用 jQuery ( https://api.jquery.com/jQuery.parseXML/ )。它还解析 XML 字符串,但为您提供了一个非常简单易用的 API,用于查找元素并获取内容或其属性的值。

显然,这个问题之前已经被问过。这是一个示例:XML 到 JavaScript 对象


推荐阅读