speedwell
speedwell

Reputation: 655

Iterating over child nodes in XML file with JavaScript using XPath

Given a legacy input XML file of the form:

<?xml version="1.0" ?>
<data>
<map>
    <key>title</key>
    <string>A Title Here</string>

    <key>description</key>
    <string>Description goes here</string>

    <key>elements</key>

    <map>
      <key>item1</key>
      <map>
        <key>name</key>
        <string>foo</string>
        <key>url</key>
        <string>http://foo.com</string>
      </map>

      <key>item2</key>
      <map>
        <key>name</key>
        <string>bar</string>
        <key>url</key>
        <string>http://bar.com</string>
      </map>

      <key>item3</key>
      <map>
        <key>name</key>
        <string>flasm</string>
        <key>url</key>
        <string>http://flasm.com</string>
      </map>

    </map>
</map>

using Javascript, I want to find the 'elements' tag (not always in the same place) and then iterate over all its children ('item' N) and gather the key/string pairs for each (e.g. "name=foo")

I've tried to do it a number of ways using DOMReader and Xpath but have not been able to get it quite right.

Can anyone show me how best to do this?

(This doesn't look like other XML I've seen so maybe that's why I'm having trouble using this in the examples I've found but as I said, it's legacy and I have no control over it).

Many thanks.

Upvotes: 0

Views: 633

Answers (1)

JWiley
JWiley

Reputation: 3219

I'm not entirely sure what you mean by "not always in the same place", if you could elaborate on that I may be able to supply a better answer. But if "elements" and its children (in your example, 'ItemN' is not a child, but a sibling) can be nested differently, you could search by just the text content like so:

//*[contains(text(), 'elements')]/following-sibling::map/key[contains(text(), 'item1')]/following-sibling::map[1]

This would give you the pairs you're looking for, if the child nodes you're looking for are in fact the next direct sibling as in your example.

Upvotes: 1

Related Questions