【问题标题】:Applescript XML "Invalid Index" with CDATA带有 CDATA 的 Applescript XML“无效索引”
【发布时间】:2017-08-27 15:50:13
【问题描述】:

使用以下脚本解析以下 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的部分修改版

如果您删除 &lt;![CDATA[Yo]]&gt; 部分并运行脚本,您会看到它按预期工作。

【问题讨论】:

    标签: xml applescript


    【解决方案1】:

    使用引用的对象,像这样:

    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
    

    或者在whose子句上使用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
    

    【讨论】:

      猜你喜欢
      • 2014-09-14
      • 2016-11-24
      • 2018-05-19
      • 1970-01-01
      • 1970-01-01
      • 2010-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多