2017-04-02 46 views
0

使用以下脚本解析以下XML会引发“无效索引”错误。我已经将它隔离为CDATA未包裹在标签内。看起来,该脚本将CDATA作为初始读取中的有效元素进行计数,但不会在随后的读取中使用它,从而抛弃索引并选择错误的元素。使用CDATA Applescript XML“无效索引”

我该如何解决这个问题?

的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]]>部分和运行脚本,你会看到它按预期工作。

回答

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