Parsing XML Data with System Events

Hi there!

I’ve got some xml data in a variable, not a file. Been trying to parse it without success. Here’s an example:

set TheXml to "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<theapp>
	<version>1</version>
</theapp >" as Unicode text
tell application "System Events"
	set TheXml to XML data
	set TheData to XML elements of TheXml
end tell

Any idea anyone? How could I just get to the data 1 in the Attribute “version”?

There is a thread that might help you…

http://bbs.applescript.net/viewtopic.php?pid=69774

I’m sorry, but it doesn’t solve the variable issue. It only covers XML data in a file, not in a variable (I’m getting the data from a server).

Any other suggestions?

Thanks for your help.

Micha

Hi Micha,

the XML commands of System Events work only reading the data from a file.
I recommend to save your text temporarily into a file and then parse the data
like this

set tempFile to (((path to desktop) as Unicode text) & "XMLtemp.txt")
set TheXml to "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<theapp>
	<version>1</version>
</theapp >" as Unicode text

set ff to open for access file tempFile with write permission
write TheXml to ff
close access ff

tell application "System Events"
	tell contents of XML file tempFile
		set TheData to XML elements
	end tell
end tell

set del to button returned of (display dialog "Delete \"XMLtemp.txt\" immediately?" buttons {"Cancel", "Delete"})
if del is "Delete" then do shell script "rm " & quoted form of POSIX path of tempFile

I get an empty set, Stephan :rolleyes:

really? the variable theData contains the XML element(s) of the file.
try this

set tempFile to (((path to desktop) as Unicode text) & "XMLtemp.txt")
set TheXml to "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<theapp>
	<version>1</version>
</theapp >" as Unicode text

set ff to open for access file tempFile with write permission
write TheXml to ff
close access ff

tell application "System Events"
	tell contents of XML file tempFile
		set TheData to XML element 1 of XML element 1
		tell TheData to set {theName, theValue} to {name, value}
	end tell
end tell

display dialog theName & ": " & theValue
--> version: 1

set del to button returned of (display dialog "Delete tempFile immediately?" buttons {"Cancel", "Delete"})
if del is "Delete" then do shell script "rm " & quoted form of POSIX path of tempFile

C’est bon :wink:

Am I correct in thinking that the XML suite can read XML, but it can’t edit it (despite Apple’s description)?

As far as I know, yes, but you can modify XML data with the XML Tools.osax