Message Boards Message Boards

2 Replies
3 Total Likes
View groups...
Share this post:

Newbie question about .XML and XMLObject

Posted 11 years ago
I am new to using XML within Mathematica.  I've done a quick glance through the docs, but I am hopeful that someone may have a simple solution that I can modify for my own purposes.

I have an XML file and a snippet of that file looks like this:

<?xml version="1.0"?>

<VTKFile type="UnstructuredGrid" version="0.1" byte_order="LittleEndian">
 <Piece NumberOfPoints="174186" NumberOfCells="963703">
      <DataArray type="Float32" NumberOfComponents="3" format="ascii"> 
         -1.000000000000000e+03 -1.000000000000000e+03 0.000000000000000e+00 
         -9.000000000000000e+02 -1.000000000000000e+03 0.000000000000000e+00 
         -8.000000000000000e+02 -1.000000000000000e+03 0.000000000000000e+00:
tons of similar data

I'd like to extract that data.

Here is what I have tried:
 garb = Import[
    "that_file_above.vtu", "XML"];
 grabElement[object_, string_] := Cases[object,
   XMLElement[string, _, _], Infinity]
 pts1 = grabElement[grabElement[garb, "Points"], "DataArray"] (*works fine*)
 pts = pts1[[1, 3]] (*list of strings, some elements are [\Ellipses] *)
ToExpression[pts] (*failure... probably because the "e" in 1.0000000e+03 is getting parsed as an undefined symbol*)

I'm hopeful that someone who is familiar with such things has an easy answer they can share with me.
Thanks, WCC
POSTED BY: W. Craig Carter
2 Replies
Please try this
 grab = ImportString["<?xml version='1.0'?>
 <VTKFile type='UnstructuredGrid' version='0.1' \
 <Piece NumberOfPoints='174186' NumberOfCells='963703'>
 <DataArray type='Float32' NumberOfComponents='3' \
 -1.000000000000000e+03 -1.000000000000000e+03 \
-9.000000000000000e+02 -1.000000000000000e+03 \
-8.000000000000000e+02 -1.000000000000000e+03 \
</VTKFile>", "XML"];

grabElement[object_, string_] :=
Cases[object, XMLElement[string, _, _], Infinity]

pts1 = grabElement[grabElement[grab, "Points"], "DataArray"]
pts = pts1[[1, 3]]

ImportString[pts[[1]], "Table"]
If you examining the Head for pts[[1]] you will find that the xml text node is a String. Once you know that the questions is how would you process a string in that format in Mathematica. There would be side effects if the format is more complicated than what you represented. If the Import functions fail to transform the data properly. You may have to add more options such as delimiters, escape characters etc.

POSTED BY: Hans Michel
Works like a charm. All this time and learning about new functions that I didn't know about.
Thanks. WCC
POSTED BY: W. Craig Carter
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract