10
$\begingroup$

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?

$\endgroup$
10
$\begingroup$

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"}]}
$\endgroup$
  • 2
    $\begingroup$ Also usable: test = StringMatchQ[#, "*XML*"] &; Cases[xmlDoc, XMLElement["item", _, {s_String?test}], Infinity] $\endgroup$ – Mr.Wizard Jul 2 '12 at 10:48
  • 1
    $\begingroup$ Mathematica does not seem to offer an elegant solution in this case. $\endgroup$ – sakra Jul 4 '12 at 18:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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