Question

I have the following xml:

<GetPurchaseContractResponse xmlns="http://payments.amazon.com/checkout/v2/2010-08-31/">
    <GetPurchaseContractResult>
        <PurchaseContract>
            <Id>amzn1.contract.1.1.1.d6779be6bf481167fe945</Id>
            <State>ACTIVE</State>
            <MerchantId>XXXXXXXXXX</MerchantId>
            <ExpirationTimeStamp>2012-07-19T10:55:28.134Z</ExpirationTimeStamp>
            <MarketplaceId>A1SDFERWERSDF</MarketplaceId>
        </PurchaseContract>
    </GetPurchaseContractResult>
    <ResponseMetadata>
        <RequestId>0db53477-d17a-11e1-ac3e-fd3e0de62222</RequestId>
    </ResponseMetadata>
</GetPurchaseContractResponse>

I want to extract the content of the ExpirationTimeStamp element.

Here is the relevant piece of my code (yes we're using jscript and not vbscript):

var xmlDoc = Server.CreateObject("Msxml2.DOMDocument.6.0");
xmlDoc.loadXML(xml);
var expNode = xmlDoc.getElementsByTagName("ExpirationTimeStamp");
if (expNode)
    Response.Write(expNode.text);

I have also tried selectSingleNode instead of getElementsByTagName

I have tried GetPurchaseContractResponse/GetPurchaseContractResult/PurchaseContract/ExpirationTimeStamp as the xpath string with none, one and two leading forward slashes

Response.Write(xmlDoc.xml) outputs the entire document, so it is loading fine.

The expNode variable doesn't get anything in it.

My knowledge of xpath is next to nothing, so I'm sure some expert out there can point out the simple mistake I am making.

Was it helpful?

Solution

Use this:

var xmlDoc = Server.CreateObject("Msxml2.DOMDocument.3.0");   
xmlDoc.loadXML(xml);   
var expNode = xmlDoc.documentElement.selectSingleNode("GetPurchaseContractResult/PurchaseContract/ExpirationTimeStamp");   
if (expNode)   
    Response.Write(expNode.text);  

Some other "experts" may note that I'm cheating here. The main problem with using XPath here is that your xml specifies a default namespace. XPath always has "no namespace" as its default namespace so to use XPath against this XML you would need to first specify a namespace alias and then use it to prefix all the names in the XPath.

Instead I'm using version 3 of MSXML which defaults to XSL Pattern (not XPath) as its selection language. XSL Pattern ignores namespaces and aliases so for simple scenario its a more straight-forward to use.

If you want to use MSXML6 you can use .setProperty("SelectionLanguage", "XSL Pattern");.

If you want to use MSXML6 and XPath you can use .setProperty("SelectionNamespaces", xmlns:a='http://payments.amazon.com/checkout/v2/2010-08-31/'");, then your XPath becomes a:GetPurchaseContractResult/a:PurchaseContract/a:ExpirationTimeStamp.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top