1

This isn't really S3-specific, it's more just a basic JavaScript question. Is there a way I can get JavaScript to give me a multidimensional array of all the data from an XML file? For example, say I've got this:

<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <Name>bucketname</Name>
  <Prefix/>
  <Marker/>
  <MaxKeys>1000</MaxKeys>
  <IsTruncated>false</IsTruncated>
  <Contents>
    <Key>image.png</Key>
    <LastModified>2011-04-05T19:22:29.000Z</LastModified>
    <ETag>"53b61a2200856713abefa6949550e09a"</ETag>
    <Size>291842</Size>
    <Owner>
      <ID>
        96796a91be9047be08fae41526548b98c4499255d00abaf23f40f1d6e6398260
      </ID>
      <DisplayName>me</DisplayName>
    </Owner>
    <StorageClass>STANDARD</StorageClass>
  </Contents>
  <Contents>
    <Key>archive.zip</Key>
    <LastModified>2011-04-29T19:05:25.000Z</LastModified>
    <ETag>"16021b5e151a69b15b4fa648a28fb112"</ETag>
    <Size>119042</Size>
    <Owner>
      <ID>
        96796a91be9023be08fae41526548b98c5699255d00aaaf23f40f1d6e6398260
      </ID>
      <DisplayName>me</DisplayName>
    </Owner>
    <StorageClass>STANDARD</StorageClass>
  </Contents>
  <Contents>
    <Key>script.sh</Key>
    <LastModified>2011-03-11T16:02:53.000Z</LastModified>
    <ETag>"4e7ec24f635835a91663be368b372a1c"</ETag>
    <Size>124714</Size>
    <Owner>
      <ID>
        96796a91be90b5be0cfae41526548b98c4495255d00caaf23f40f1d6e6398260
      </ID>
      <DisplayName>me</DisplayName>
    </Owner>
    <StorageClass>STANDARD</StorageClass>
  </Contents>
</ListBucketResult>

I'd like to be able to iterate through each <Contents> block, and run some code based on its contents. I know this is possible, but all the tutorials I've seen look a lot harder than they should be.

svick
  • 236,525
  • 50
  • 385
  • 514
Dan Hlavenka
  • 3,697
  • 8
  • 42
  • 60
  • One of the generic "parse XML with Javascript" answers should help. http://stackoverflow.com/search?q=javascript+parse+xml – Pekka Oct 09 '11 at 07:30

1 Answers1

0

https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript explains how to use XPath from JavaScript. You just need to come up with an XPath query that describes the results you wanted, and use that API to get the results.

If you get your XML via XHR, then you already have a parsed DOM handy in the result, but if not, see XML parsing of a variable string in JavaScript

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245