1

I have the following XML

<plist version="1.0">
    <dict>
        <key>items</key>
        <array>
            <dict>
                <key>assets</key>
                <array>
                    <dict>
                        <key>kind</key>
                        <string>software-package</string>
                        <key>url</key>
                        <string>test1</string>
                    </dict>
                </array>
                <key>metadata</key>
                <dict>
                    <key>bundle-identifier</key>
                    <string>test</string>
                    <key>bundle-version</key>
                    <string>1.0</string>
                    <key>kind</key>
                    <string>software</string>
                    <key>subtitle</key>
                    <string>pixTraining</string>
                    <key>title</key>
                    <string>test</string>
                </dict>
            </dict>
        </array>
    </dict>
</plist>

if I use this XPath in an xml editor

/plist/dict/array/dict/dict/string[2]

I get back the version. But when I have the same code in JavaScript, I don't get any thing back. Here is my JavaScript code

var elements = doc.evaluate('//plist/dict/array/dict/dict/string[2]');

I don't get anything back. elements is coming as undefined. Any clues why?

2 Answers 2

1

https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript

Here you have tutorial how to accomplish that.

Maybe you can check whether

var elements = doc.evaluate('//plist/');

is not null and then go futher.

Sign up to request clarification or add additional context in comments.

Comments

1

@Kooilnc is on the right track, but it seems that Firefox is picky about the XPathResult type that you specify. I would expect XPathResult.ANY_TYPE to work, but it does not. In my tests only UNORDERED_NODE_SNAPSHOT_TYPE and ORDERED_NODE_SNAPSHOT_TYPE worked.

For example:

var result = doc.evaluate("/plist/dict/array/dict/dict/string[2]", 
                doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
result.snapshotItem(0); // access the element

Note that evaluate returns a set of matched nodes. Use snapshotItem to access the first in the set. If your expression returns more than one node, you can iterate over them like this:

for (var i = 0; i < result.snapshotLength; i++) {
    console.log(result.snapshotItem(i));
}

Further reading:

1 Comment

Thanks for the response, seems like I can't use Level 3 DOM API in the javascript I'm using on Titanium. I get an an XPathResult not found. I will have to do it the old way which is iterating and checking for the nodes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.