在 Applescript 中使用 XML 属性

Using XML attributes in Applescript

所以我最近发现了 XML-Parsing in Applescript。我想解析具有如下结构的 XML 文件:

<example>
    <sample value="hello world"/>
</example>

所以我尝试了这样的事情:

tell application "System Events"
    tell XML file "/path/to/the/file.xml"
        tell XML element "example"
            return XML attribute "value" of XML element "sample"
        end tell
    end tell
end tell

但是,错误显示:

System Events got an error: Can’t get XML element "example" of XML file "~/Desktop/xml.xml" number -1728.

根据MacErrors.hnumber -1728表示errAENoSuchObject,所以没有找到这样的对象。我做错了什么?

你几乎成功了:

return XML attribute "value" of XML element "sample"

应该是:

return the value of XML attribute "value" of XML element "sample"

这对我有用:

tell application "System Events"
    tell XML file "/path/to/the/file.xml"
        tell XML element "example"
            return the value of XML attribute "value" of XML element "sample"
        end tell
    end tell
end tell



终端:

% file foobar.xml
foobar.xml: XML 1.0 document text, ASCII text
% cat foobar.xml
<?xml version="1.0" encoding="UTF-8"?>
<example>
    <sample value="hello world"/>
</example>
% 

脚本编辑器中: