Classic ASP .loadXML(XMLstring) 读出空白?
Classic ASP .loadXML(XMLstring) reads out blank?
我正在使用经典 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>
好吧,在测试你的代码后,不是 Charset
属性 导致问题 (但我会确保它设置为 UTF-8
无论如何) .
问题是 XML 解析失败,在检查 parseError
时发现了这个问题;
-1072896749 - Whitespace is not allowed at this location.
然后我看了一下你发的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
的文件夹的物理位置,并为匿名帐户提供写入该文件夹所需的权限。您不必执行任何这些操作,我只是在解释为什么代码看起来不同。
正在解析XML
有两点需要指出。
loadXML()
方法 return 是一个布尔值,告诉您 XML 是否成功加载。如果 return 值为 False
使用 parseError
对象检索解析器在验证 XML.
时遇到的最后一个错误
在上面的示例中,我将其作为 HTTP 400 Bad Request
响应传回,并将 errorCode
和 Reason
属性作为消息正文。
相关
Accessing a request's body (Credit to @kul-tigin 用于 BytesToStr()
函数)
公认的解决方案绝对是问题的答案。
但我想展示与 MS 鲜为人知的功能相关的其他方法XML。
这,处理 XML 请求正文也可以以更可靠的二进制安全方式完成,无需字符串转换、可能的字符集/编码问题等。
load method can handle ASP's Request object, a Stream object (or an object implements IStream) 或 unsigned 字节的 SAFEARRAY。
Parameters
xmlSource[in]
An indicator of the source XML to parse. This may be an URL (String/BSTR), a Request object (in an ASP page) [1], an IStream [3],
SAFEARRAY of bytes (VT_ARRAY|VT_UI1) [2], a DOMDocument object, or any
object that supports IStream, ISequentialStream, or IPersistStream.
See Remarks for more information. isSuccessful[out, retval]
基于Lankymart's解决方案(感谢感谢顺便说一句),从简单到复杂:
方法#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)
'[...]
希望对您有所帮助。
我正在使用经典 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>
好吧,在测试你的代码后,不是 Charset
属性 导致问题 (但我会确保它设置为 UTF-8
无论如何) .
问题是 XML 解析失败,在检查 parseError
时发现了这个问题;
-1072896749 - Whitespace is not allowed at this location.
然后我看了一下你发的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
的文件夹的物理位置,并为匿名帐户提供写入该文件夹所需的权限。您不必执行任何这些操作,我只是在解释为什么代码看起来不同。
正在解析XML
有两点需要指出。
loadXML()
方法 return 是一个布尔值,告诉您 XML 是否成功加载。如果 return 值为 False
使用 parseError
对象检索解析器在验证 XML.
在上面的示例中,我将其作为 HTTP 400 Bad Request
响应传回,并将 errorCode
和 Reason
属性作为消息正文。
相关
Accessing a request's body (Credit to @kul-tigin 用于
BytesToStr()
函数)
公认的解决方案绝对是问题的答案。
但我想展示与 MS 鲜为人知的功能相关的其他方法XML。
这,处理 XML 请求正文也可以以更可靠的二进制安全方式完成,无需字符串转换、可能的字符集/编码问题等。
load method can handle ASP's Request object, a Stream object (or an object implements IStream) 或 unsigned 字节的 SAFEARRAY。
Parameters
xmlSource[in]
An indicator of the source XML to parse. This may be an URL (String/BSTR), a Request object (in an ASP page) [1], an IStream [3], SAFEARRAY of bytes (VT_ARRAY|VT_UI1) [2], a DOMDocument object, or any object that supports IStream, ISequentialStream, or IPersistStream. See Remarks for more information. isSuccessful[out, retval]
基于Lankymart's解决方案(感谢感谢顺便说一句),从简单到复杂:
方法#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)
'[...]
希望对您有所帮助。