Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have imported an XML document into Mathematica. It is now represented as Symbolic XML expression in the variable xml:

XMLObject["Document"][{XMLObject["Declaration"]["Version" -> "1.0"]}, 
 XMLElement[
  "slideshow", {}, {XMLElement["title", {}, {"XML Tutorial"}], 
   XMLElement[
    "slide", {}, {XMLElement["title", {}, {"Agenda"}], 
     XMLElement["item", {}, {"Introduction"}], 
     XMLElement["item", {}, {"XML technologies"}], 
     XMLElement["item", {}, {"Editors for XML documents"}]}]}], {}]

Using the Cases function I want to extract the XMLElement expressions whose plain text contents contain the word "XML":

Cases[xml, XMLElement["item", _, {___ ~~ "XML" ~~ ___}], Infinity]

This however returns the empty list, probably because it is mixing a Mathematica expression pattern with a string expression pattern. How does one go about embedding a string pattern into a regular pattern?

share|improve this question
2  
Not fully related, but I think this a must-read piece of text for anyone matching a *ML kind of thing. stackoverflow.com/a/1732454/353410 –  belisarius Jun 30 '12 at 15:10

1 Answer 1

up vote 8 down vote accepted

I'd have used StringMatchQ[] if I was in your shoes:

xmlDoc = XMLObject[
    "Document"][{XMLObject["Declaration"]["Version" -> "1.0"]}, 
   XMLElement[
    "slideshow", {}, {XMLElement["title", {}, {"XML Tutorial"}], 
     XMLElement[
      "slide", {}, {XMLElement["title", {}, {"Agenda"}], 
       XMLElement["item", {}, {"Introduction"}], 
       XMLElement["item", {}, {"XML technologies"}], 
       XMLElement["item", {}, {"Editors for XML documents"}]}]}], {}];

Cases[xmlDoc, XMLElement["item", _, {s_String /; 
    StringMatchQ[s, ___ ~~ "XML" ~~ ___]}], Infinity]

which yields

{XMLElement["item", {}, {"XML technologies"}], 
 XMLElement["item", {}, {"Editors for XML documents"}]}
share|improve this answer
2  
Also usable: test = StringMatchQ[#, "*XML*"] &; Cases[xmlDoc, XMLElement["item", _, {s_String?test}], Infinity] –  Mr.Wizard Jul 2 '12 at 10:48
    
Mathematica does not seem to offer an elegant solution in this case. –  sakra Jul 4 '12 at 18:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.