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$
1

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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