我使用经典的ASP来解析从eBay api发送的SOAP XML通知。我正在给自己发布一个来自api文档的测试示例SOAP消息。我能够收到XML数据字符串。当我将数据转换为字符串并将xmlString输出到文本文件中时,收到的XML就在那里。
当我将XML(xmlString)加载到DOMDocument对象并尝试输出它时,我得到的只是3个空白行。我试图循环遍历元素并解析它们,但它在DOM对象中似乎是空白的,因为我在寻找节点的行上获得了Object Required错误。
这是我的代码,以及我发布的XML消息(使用Postmaster应用程序)一点指导将不胜感激!
<%
Function BytesToStr(bytes)
Dim Stream
Set Stream = Server.CreateObject("Adodb.Stream")
Stream.Type = 1 'adTypeBinary
Stream.Open
Stream.Write bytes
Stream.Position = 0
Stream.Type = 2 'adTypeText
Stream.Charset = "iso-8859-1"
BytesToStr = Stream.ReadText
Stream.Close
Set Stream = Nothing
End Function
Dim isPost: isPost = (UCase(Request.ServerVariables("REQUEST_METHOD") & "") = "POST")
'Is it a HTTP POST?
If isPost Then
If Request.TotalBytes > 0 Then
Dim lngBytesCount, xmlString
lngBytesCount = Request.TotalBytes
xmlString = BytesToStr(Request.BinaryRead(lngBytesCount))
Dim xdoc
set xdoc = CreateObject("Msxml2.DOMDocument.6.0")
xdoc.async = false
xdoc.loadXML(xmlString)
call xdoc.setProperty("SelectionNamespaces", "xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='urn:ebay:apis:eBLBaseComponents'")
'**I commented this next part out because I was getting Error:Object Requred
'**I couldnt get any XML from xdoc to print at all
'**see below: WriteLine(xdoc.xml)
'Dim node
'For Each node in xdoc.selectSingleNode("/soapenv:Body/GetItemResponse").ChildNodes
' sResult = sResult & node.xml
'Next
dim fs, tfile
set fs=Server.CreateObject("Scripting.FileSystemObject")
set tfile=fs.OpenTextFile("C:\inetpub\wwwroot\ASPtest\_notification3.txt", 8, True)
tfile.WriteLine(xdoc.xml)
tfile.WriteLine("")
tfile.Close
set tfile=nothing
set fs=nothing
End If
'Let sender know we have received and processing the message.
Response.Status = "200 OK"
Else
'Return method not allowed
Response.Status = "405 Method Not Allowed"
End If
Response.End
%>
发布的示例SOAP消息(来自邮递员应用程序):
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://
www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header>
<ebl:RequesterCredentials soapenv:mustUnderstand="0" xmlns:ns="urn:ebay:apis:eBLBaseComponents"
xmlns:ebl="urn:ebay:apis:eBLBaseComponents">
<ebl:NotificationSignature xmlns:ebl="urn:ebay:apis:eBLBaseComponents">Z2yhKdKmS0Ga5VPmLDOAlg==</
ebl:NotificationSignature>
</ebl:RequesterCredentials>
</soapenv:Header>
<soapenv:Body>
<GetItemResponse xmlns="urn:ebay:apis:eBLBaseComponents">
<Timestamp>2008-02-13T03:47:28.106Z</Timestamp>
<Ack>Success</Ack>
<CorrelationID>137541140</CorrelationID>
<Version>553</Version>
<Build>e553_core_Bundled_6057805_R1</Build>
<NotificationEventName>ItemSold</NotificationEventName>
<RecipientUserID>Seller1</RecipientUserID>
<Item>
<AutoPay>false</AutoPay>
<BuyerProtection>ItemEligible</BuyerProtection>
<BuyItNowPrice currencyID="USD">10.0</BuyItNowPrice>
<Country>US</Country>
<Currency>USD</Currency>
<GiftIcon>0</GiftIcon>
<HitCounter>NoHitCounter</HitCounter>
<ItemID>250000627102</ItemID>
<ListingDetails>
<Adult>false</Adult>
<BindingAuction>false</BindingAuction>
<CheckoutEnabled>true</CheckoutEnabled>
<ConvertedBuyItNowPrice currencyID="USD">10.0</ConvertedBuyItNowPrice>
<ConvertedStartPrice currencyID="USD">1.0</ConvertedStartPrice>
<ConvertedReservePrice currencyID="USD">0.0</ConvertedReservePrice>
<HasReservePrice>false</HasReservePrice>
<StartTime>2008-02-13T03:42:45.000Z</StartTime>
<EndTime>2008-02-13T03:43:32.000Z</EndTime>
<ViewItemURL>http://cgi.qa-api012.qa.ebay.com/ws/eBayISAPI.dll?ViewItem&item=250000627102&category=1463</ViewItemURL>
<HasUnansweredQuestions>false</HasUnansweredQuestions>
<HasPublicMessages>false</HasPublicMessages>
<ExpressListing>false</ExpressListing>
<ViewItemURLForNaturalSearch>http://cgi.qa-api012.qa.ebay.com/Test-Item-Won-Sold-notify_W0QQitemZ250000627102QQcategoryZ1463QQcmdZViewItem</ViewItemURLForNaturalSearch>
</ListingDetails>
<ListingDuration>Days_5</ListingDuration>
<ListingType>Chinese</ListingType>
<Location>San Jose, CA</Location>
<PaymentMethods>PaymentSeeDescription</PaymentMethods>
<PaymentMethods>PayPal</PaymentMethods>
<PayPalEmailAddress>ve2@aol.com</PayPalEmailAddress>
<PrimaryCategory>
<CategoryID>1463</CategoryID>
<CategoryName>Collectibles:Trading Cards:Phone Cards</CategoryName>
</PrimaryCategory>
<PrivateListing>false</PrivateListing>
<Quantity>1</Quantity>
<ReservePrice currencyID="USD">0.0</ReservePrice>
<ReviseStatus>
<ItemRevised>false</ItemRevised>
</ReviseStatus>
<Seller>
<AboutMePage>false</AboutMePage>
<Email>seller@email.com</Email>
<FeedbackScore>100</FeedbackScore>
<PositiveFeedbackPercent>98.1</PositiveFeedbackPercent>
<FeedbackPrivate>false</FeedbackPrivate>
<FeedbackRatingStar>Turquoise</FeedbackRatingStar>
<IDVerified>false</IDVerified>
<eBayGoodStanding>true</eBayGoodStanding>
<NewUser>false</NewUser>
<RegistrationDate>2004-02-23T23:50:13.000Z</RegistrationDate>
<Site>US</Site>
<Status>Confirmed</Status>
<UserID>Seller1</UserID>
<UserIDChanged>false</UserIDChanged>
<UserIDLastChanged>2004-02-23T23:48:54.000Z</UserIDLastChanged>
<VATStatus>NoVATTax</VATStatus>
<SellerInfo>
<AllowPaymentEdit>true</AllowPaymentEdit>
<CheckoutEnabled>true</CheckoutEnabled>
<CIPBankAccountStored>false</CIPBankAccountStored>
<GoodStanding>true</GoodStanding>
<MerchandizingPref>OptIn</MerchandizingPref>
<QualifiesForB2BVAT>false</QualifiesForB2BVAT>
<SellerLevel>None</SellerLevel>
<StoreOwner>false</StoreOwner>
<ExpressEligible>false</ExpressEligible>
<ExpressWallet>false</ExpressWallet>
<SafePaymentExempt>true</SafePaymentExempt>
</SellerInfo>
<MotorsDealer>false</MotorsDealer>
</Seller>
<SellingStatus>
<BidCount>2</BidCount>
<BidIncrement currencyID="USD">0.25</BidIncrement>
<ConvertedCurrentPrice currencyID="USD">1.25</ConvertedCurrentPrice>
<CurrentPrice currencyID="USD">1.25</CurrentPrice>
<HighBidder>
<AboutMePage>false</AboutMePage>
<EIASToken>nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6wJkoWoCJaGoAmdj6x9nY+seQ==</EIASToken>
<Email>buyer@email.com</Email>
<FeedbackScore>5</FeedbackScore>
<PositiveFeedbackPercent>100.0</PositiveFeedbackPercent>
<FeedbackPrivate>false</FeedbackPrivate>
<FeedbackRatingStar>None</FeedbackRatingStar>
<IDVerified>false</IDVerified>
<eBayGoodStanding>true</eBayGoodStanding>
<NewUser>false</NewUser>
<RegistrationDate>2004-02-24T07:00:00.000Z</RegistrationDate>
<Site>US</Site>
<Status>Confirmed</Status>
<UserID>Buyer1</UserID>
<UserIDChanged>false</UserIDChanged>
<UserIDLastChanged>2004-02-24T07:00:00.000Z</UserIDLastChanged>
<VATStatus>NoVATTax</VATStatus>
<BuyerInfo>
<ShippingAddress>
<Country>US</Country>
<PostalCode>95125</PostalCode>
</ShippingAddress>
</BuyerInfo>
<UserAnonymized>false</UserAnonymized>
</HighBidder>
<LeadCount>0</LeadCount>
<MinimumToBid currencyID="USD">1.5</MinimumToBid>
<QuantitySold>1</QuantitySold>
<ReserveMet>true</ReserveMet>
<SecondChanceEligible>true</SecondChanceEligible>
<ListingStatus>Completed</ListingStatus>
</SellingStatus>
<ShippingDetails>
<AllowPaymentEdit>true</AllowPaymentEdit>
<ApplyShippingDiscount>false</ApplyShippingDiscount>
<InsuranceOption>NotOffered</InsuranceOption>
<SalesTax>
<SalesTaxPercent>0.0</SalesTaxPercent>
<ShippingIncludedInTax>false</ShippingIncludedInTax>
</SalesTax>
<ThirdPartyCheckout>false</ThirdPartyCheckout>
<TaxTable/>
</ShippingDetails>
<ShipToLocations>US</ShipToLocations>
<Site>US</Site>
<StartPrice currencyID="USD">1.0</StartPrice>
<TimeLeft>PT0S</TimeLeft>
<Title>Test Item{Won/Sold} notify</Title>
<HitCount>0</HitCount>
<GetItFast>false</GetItFast>
<PostalCode>
</PostalCode>
<PictureDetails>
<PhotoDisplay>None</PhotoDisplay>
</PictureDetails>
<ProxyItem>false</ProxyItem>
</Item>
</GetItemResponse>
</soapenv:Body>
</soapenv:Envelope>
答案 0 :(得分:4)
在测试代码之后,它不是导致问题的Charset
属性(但我会确保它设置为UTF-8
。< / p>
问题是XML无法解析,并且在检查parseError
时发现了这个;
-1072896749 - 此位置不允许有空格。
然后我看一下你发布的XML,它确实有一些硬包装,我已经删除并再次测试,这次它成功了。
修改后的XML (删除硬包装)
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header>
<ebl:RequesterCredentials soapenv:mustUnderstand="0" xmlns:ns="urn:ebay:apis:eBLBaseComponents" xmlns:ebl="urn:ebay:apis:eBLBaseComponents">
<ebl:NotificationSignature xmlns:ebl="urn:ebay:apis:eBLBaseComponents">Z2yhKdKmS0Ga5VPmLDOAlg==</ebl:NotificationSignature>
</ebl:RequesterCredentials>
</soapenv:Header>
<soapenv:Body>
<GetItemResponse xmlns="urn:ebay:apis:eBLBaseComponents">
<Timestamp>2008-02-13T03:47:28.106Z</Timestamp>
<Ack>Success</Ack>
<CorrelationID>137541140</CorrelationID>
<Version>553</Version>
<Build>e553_core_Bundled_6057805_R1</Build>
<NotificationEventName>ItemSold</NotificationEventName>
<RecipientUserID>Seller1</RecipientUserID>
<Item>
<AutoPay>false</AutoPay>
<BuyerProtection>ItemEligible</BuyerProtection>
<BuyItNowPrice currencyID="USD">10.0</BuyItNowPrice>
<Country>US</Country>
<Currency>USD</Currency>
<GiftIcon>0</GiftIcon>
<HitCounter>NoHitCounter</HitCounter>
<ItemID>250000627102</ItemID>
<ListingDetails>
<Adult>false</Adult>
<BindingAuction>false</BindingAuction>
<CheckoutEnabled>true</CheckoutEnabled>
<ConvertedBuyItNowPrice currencyID="USD">10.0</ConvertedBuyItNowPrice>
<ConvertedStartPrice currencyID="USD">1.0</ConvertedStartPrice>
<ConvertedReservePrice currencyID="USD">0.0</ConvertedReservePrice>
<HasReservePrice>false</HasReservePrice>
<StartTime>2008-02-13T03:42:45.000Z</StartTime>
<EndTime>2008-02-13T03:43:32.000Z</EndTime>
<ViewItemURL>http://cgi.qa-api012.qa.ebay.com/ws/eBayISAPI.dll?ViewItem&item=250000627102&category=1463</ViewItemURL>
<HasUnansweredQuestions>false</HasUnansweredQuestions>
<HasPublicMessages>false</HasPublicMessages>
<ExpressListing>false</ExpressListing>
<ViewItemURLForNaturalSearch>http://cgi.qa-api012.qa.ebay.com/Test-Item-Won-Sold-notify_W0QQitemZ250000627102QQcategoryZ1463QQcmdZViewItem</ViewItemURLForNaturalSearch>
</ListingDetails>
<ListingDuration>Days_5</ListingDuration>
<ListingType>Chinese</ListingType>
<Location>San Jose, CA</Location>
<PaymentMethods>PaymentSeeDescription</PaymentMethods>
<PaymentMethods>PayPal</PaymentMethods>
<PayPalEmailAddress>ve2@aol.com</PayPalEmailAddress>
<PrimaryCategory>
<CategoryID>1463</CategoryID>
<CategoryName>Collectibles:Trading Cards:Phone Cards</CategoryName>
</PrimaryCategory>
<PrivateListing>false</PrivateListing>
<Quantity>1</Quantity>
<ReservePrice currencyID="USD">0.0</ReservePrice>
<ReviseStatus>
<ItemRevised>false</ItemRevised>
</ReviseStatus>
<Seller>
<AboutMePage>false</AboutMePage>
<Email>seller@email.com</Email>
<FeedbackScore>100</FeedbackScore>
<PositiveFeedbackPercent>98.1</PositiveFeedbackPercent>
<FeedbackPrivate>false</FeedbackPrivate>
<FeedbackRatingStar>Turquoise</FeedbackRatingStar>
<IDVerified>false</IDVerified>
<eBayGoodStanding>true</eBayGoodStanding>
<NewUser>false</NewUser>
<RegistrationDate>2004-02-23T23:50:13.000Z</RegistrationDate>
<Site>US</Site>
<Status>Confirmed</Status>
<UserID>Seller1</UserID>
<UserIDChanged>false</UserIDChanged>
<UserIDLastChanged>2004-02-23T23:48:54.000Z</UserIDLastChanged>
<VATStatus>NoVATTax</VATStatus>
<SellerInfo>
<AllowPaymentEdit>true</AllowPaymentEdit>
<CheckoutEnabled>true</CheckoutEnabled>
<CIPBankAccountStored>false</CIPBankAccountStored>
<GoodStanding>true</GoodStanding>
<MerchandizingPref>OptIn</MerchandizingPref>
<QualifiesForB2BVAT>false</QualifiesForB2BVAT>
<SellerLevel>None</SellerLevel>
<StoreOwner>false</StoreOwner>
<ExpressEligible>false</ExpressEligible>
<ExpressWallet>false</ExpressWallet>
<SafePaymentExempt>true</SafePaymentExempt>
</SellerInfo>
<MotorsDealer>false</MotorsDealer>
</Seller>
<SellingStatus>
<BidCount>2</BidCount>
<BidIncrement currencyID="USD">0.25</BidIncrement>
<ConvertedCurrentPrice currencyID="USD">1.25</ConvertedCurrentPrice>
<CurrentPrice currencyID="USD">1.25</CurrentPrice>
<HighBidder>
<AboutMePage>false</AboutMePage>
<EIASToken>nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6wJkoWoCJaGoAmdj6x9nY+seQ==</EIASToken>
<Email>buyer@email.com</Email>
<FeedbackScore>5</FeedbackScore>
<PositiveFeedbackPercent>100.0</PositiveFeedbackPercent>
<FeedbackPrivate>false</FeedbackPrivate>
<FeedbackRatingStar>None</FeedbackRatingStar>
<IDVerified>false</IDVerified>
<eBayGoodStanding>true</eBayGoodStanding>
<NewUser>false</NewUser>
<RegistrationDate>2004-02-24T07:00:00.000Z</RegistrationDate>
<Site>US</Site>
<Status>Confirmed</Status>
<UserID>Buyer1</UserID>
<UserIDChanged>false</UserIDChanged>
<UserIDLastChanged>2004-02-24T07:00:00.000Z</UserIDLastChanged>
<VATStatus>NoVATTax</VATStatus>
<BuyerInfo>
<ShippingAddress>
<Country>US</Country>
<PostalCode>95125</PostalCode>
</ShippingAddress>
</BuyerInfo>
<UserAnonymized>false</UserAnonymized>
</HighBidder>
<LeadCount>0</LeadCount>
<MinimumToBid currencyID="USD">1.5</MinimumToBid>
<QuantitySold>1</QuantitySold>
<ReserveMet>true</ReserveMet>
<SecondChanceEligible>true</SecondChanceEligible>
<ListingStatus>Completed</ListingStatus>
</SellingStatus>
<ShippingDetails>
<AllowPaymentEdit>true</AllowPaymentEdit>
<ApplyShippingDiscount>false</ApplyShippingDiscount>
<InsuranceOption>NotOffered</InsuranceOption>
<SalesTax>
<SalesTaxPercent>0.0</SalesTaxPercent>
<ShippingIncludedInTax>false</ShippingIncludedInTax>
</SalesTax>
<ThirdPartyCheckout>false</ThirdPartyCheckout>
<TaxTable/>
</ShippingDetails>
<ShipToLocations>US</ShipToLocations>
<Site>US</Site>
<StartPrice currencyID="USD">1.0</StartPrice>
<TimeLeft>PT0S</TimeLeft>
<Title>Test Item{Won/Sold} notify</Title>
<HitCount>0</HitCount>
<GetItFast>false</GetItFast>
<PostalCode>
</PostalCode>
<PictureDetails>
<PhotoDisplay>None</PhotoDisplay>
</PictureDetails>
<ProxyItem>false</ProxyItem>
</Item>
</GetItemResponse>
</soapenv:Body>
</soapenv:Envelope>
以下是帮助调试的修改代码
<%
Option Explicit
Function BytesToStr(bytes)
Dim Stream
Set Stream = Server.CreateObject("Adodb.Stream")
With Stream
.Type = 1 'adTypeBinary
.Open
.Write bytes
.Position = 0
.Type = 2 'adTypeText
.Charset = "UTF-8"
BytesToStr = .ReadText
Stream.Close
End With
Set Stream = Nothing
End Function
Dim isPost: isPost = (UCase(Request.ServerVariables("REQUEST_METHOD") & "") = "POST")
Dim lngBytesCount, xmlString
Dim xdoc, fs, tfile
Dim loaded
'Is it a HTTP POST?
If isPost Then
If Request.TotalBytes > 0 Then
lngBytesCount = Request.TotalBytes
xmlString = BytesToStr(Request.BinaryRead(lngBytesCount))
Set xdoc = CreateObject("Msxml2.DOMDocument.6.0")
xdoc.async = False
loaded = xdoc.loadXML(xmlString)
If loaded Then
Call xdoc.setProperty("SelectionNamespaces", "xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='urn:ebay:apis:eBLBaseComponents'")
'**I commented this next part out because I was getting Error:Object Requred
'**I couldnt get any XML from xdoc to print at all
'**see below: WriteLine(xdoc.xml)
'Dim node
'For Each node in xdoc.selectSingleNode("/soapenv:Body/GetItemResponse").ChildNodes
' sResult = sResult & node.xml
'Next
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set tfile=fs.OpenTextFile(Server.MapPath("/files") & "\_notification3.txt", 8, True)
Call tfile.WriteLine(xdoc.xml)
Call tfile.WriteLine("")
Call tfile.Close()
Set tfile = Nothing
Set fs = Nothing
'Let sender know we have received and processing the message.
Response.Status = "200 OK"
Response.Write "Message processed"
Else
Response.Status = "400 Bad Request"
Response.Write xdoc.parseError.errorCode & " - " & xdoc.parseError.Reason
End If
Else
Response.Status = "400 Bad Request"
Response.Write "No message was sent"
End If
Else
'Return method not allowed
Response.Status = "405 Method Not Allowed"
Response.Write "Requested method is not supported."
End If
Response.End
%>
应该指出,为了测试文件创建,我修改了路径,但系统上的硬编码路径应该可以正常工作。我对其进行了修改,以便我可以使用Server.MapPath()
映射我在网站外部调用files
的文件夹的物理位置,并为匿名帐户提供写入所需的权限。你不必做任何这些,我只是解释为什么代码看起来不同。
要指出的一切事情。
loadXML()
方法返回一个布尔值,告诉您XML是否成功加载。如果返回值为False
,则使用parseError
对象来检索解析器在验证XML时遇到的最后一个错误。
在上面的示例中,我将其作为HTTP 400 Bad Request
响应传回,其中errorCode
和Reason
属性作为邮件正文。
答案 1 :(得分:3)
接受的解决方案绝对是问题的答案。
但我想展示与MSXML鲜为人知的功能相关的其他方法。
这样,处理XML请求体也可以用更可靠的二进制安全方式完成,无需字符串转换,可能的字符集/编码问题等。
load方法可以处理ASP的Request对象,Stream对象(或对象实现IStream)或无符号字节的SAFEARRAY。
<强>参数强>
xmlSource [IN]
要解析的源XML的指示符。这可能是一个URL(字符串/ BSTR),一个Request对象(在ASP页面中) [1] ,一个IStream [3] 下, SAFEARRAY字节(VT_ARRAY | VT_UI1) [2] ,DOMDocument对象或任何 支持IStream,ISequentialStream或IPersistStream的对象。 有关详细信息,请参阅备注。 isSuccessful [out,retval]
基于Lankymart's解决方案(感谢信用BTW),从简单到复杂:
方法#1 - Request
对象
'[...]
Set xdoc = Server.CreateObject("MSXML2.DOMDocument.6.0")
xdoc.async = False
loaded = xdoc.load(Request)
'[...]
方法#2 - SAFEARRAY
'[...]
Set xdoc = Server.CreateObject("MSXML2.DOMDocument.6.0")
xdoc.async = False
loaded = xdoc.Load(Request.BinaryRead(lngBytesCount))
'[...]
方法#3 - Adodb.Stream
对象(二进制类型)
'[...]
Set xdoc = Server.CreateObject("MSXML2.DOMDocument.6.0")
xdoc.async = False
Dim binaryStream
Set binaryStream = Server.CreateObject("Adodb.Stream")
binaryStream.Type = 1 'adTypeBinary
binaryStream.Open
binaryStream.Write Request.BinaryRead(lngBytesCount)
binaryStream.Position = 0
loaded = xdoc.Load(binaryStream)
'[...]
希望它有所帮助。