Applescript XML"无效索引"与CDATA

时间:2017-04-02 20:56:48

标签: xml applescript

使用以下脚本解析以下XML会引发"无效索引"错误。我已经将CDATA包裹在标签内部的事实隔离开了。看起来该脚本将CDATA计为初始读取中的有效元素,但在后续读取中不会使用它,从而抛弃索引并选择错误的元素。

我怎样才能解决这个问题?

的example.xml:

<?xml version="1.0"?>
<library>
  <info>Some info</info>
  <![CDATA[Yo]]>
  <books>
    <book country="US">
      <name>The Secret Lives of Cats</name>
      <publisher>Feline Press</publisher>
    </book>
  </books>
</library>

剧本:

tell application "System Events"
    tell XML file "~/Downloads/example.xml"
        set books to every XML element of XML element "books" of XML element "library" whose name is "book"
        repeat with a from 1 to length of books
            set theBook to item a of books
            tell theBook
                name of every XML element
                name of every XML attribute
                value of every XML attribute
            end tell
        end repeat
    end tell
end tell

注意,该示例是https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/WorkwithXML.html

的部分修改版本

如果您删除<![CDATA[Yo]]>部分并运行该脚本,则会看到它按预期工作。

1 个答案:

答案 0 :(得分:0)

使用引用的对象,如下所示:

tell application "System Events"
    tell XML file "~/Downloads/example.xml"
        set ref_books to a reference to (XML elements of XML element "books" of XML element "library" whose name is "book")
        repeat with theBook in ref_books
            tell theBook
                name of every XML element
                name of every XML attribute
                value of every XML attribute
            end tell
        end repeat
    end tell
end tell

或者使用其子句上的tell块,如下所示:

tell application "System Events"
    tell XML file "~/Downloads/example.xml""
        tell (XML elements of XML element "books" of XML element "library" whose name is "book")
            repeat with theBook in it
                tell theBook
                    name of every XML element
                    name of every XML attribute
                    value of every XML attribute
                end tell
            end repeat
        end tell
    end tell
end tell