2017-04-02 47 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