shell
XML.com: XSH, An XML Editing Shell
Articles | Weblogs | Newsletter | Safari Bookshelf Listen
Print
Subscribe to XML
XSH, An XML Editing Shell
by Kip Hampton
July 10, 2002
IntroductionA few months ago we briefly examined some of the command lineutilities available to users of Perl and XML. This month we will continuein that vein by looking at the 300-pound gorilla of Perl/XML command linetools, Petr Pajas' intriguing XML::XSH.XML::XSH and the xsh executable provide a richshell environment which makes performing common XML-related tasks as terseand straightforward as using a UNIX shells like bash orcsh. Yes, that's right -- an XML editing shell. As we will see,it's not as crazy as it seems.xsh BasicsBefore we look at xsh's advanced tricks, let's get familiarwith the environment it provides. We'll begin by starting thexsh shell:
[user@host user] xsh -i-----------------------------------------------------xsh - XML Editing Shell version 0.9 (Revision: 1.6)-----------------------------------------------------...xsh scratch:/>The xsh shell starts in interactive mode, creating a newdefault scratch pad document, called new_document.xml with theID scratch. The shell prompt takes the form of the currentdocument's ID (scratch, in this case), followed by a colon, and then thecurrent working context within that document expressed as an XPath location(/, in this case). In other words, we can tell from the prompt that we are atthe root (/) level of the current XML document, whose ID isscratch.We can open an existing XML document from the file system in order tofigure out how to navigate within and between documents:xsh scratch:/> open cams=files/camelids.xmlparsing files/camelids.xmldone.xsh cams:/>The open command opens the document camelids.xmlfrom the directory files in the same directory in which westarted the xsh shell, assigns it the ID of cams,and changes the working context to the root (/) of that document.To list the elements contained in the current context we use thels command.xsh cams:/> ls...Found 1 node(s).xsh cams:/>Also in Perl and XMLOSCON 2002 Perl and XML ReviewPDF Presentations Using AxPointMulti-Interface Web Services Made EasyPerl and XML on the Command LineIntroducing XML::SAX::Machines, Part TwoSince the current context is the abstract root of the document, we see theXML declaration and the sole top-level element.If our document contained processing instructions or a Document TypeDefinition between the XML declaration and the top-level element, they wouldappear here, too.Right through here is where is where things get interesting. Just like itsUNIX shell cousins, many of xsh's commands accept paths asarguments, specifying the context in which that command is evaluated. Thedifference is that in xsh those paths are XPath expressionswhich provide access to the contents of the open XML documents, rather thanfile system paths that provide an interface to the files and directories ofthe mounted volumes.So, for example, if we wanted list all of the elements in our camelids document, we need only supply the appropriate XPathexpression to the ls command:xsh cams:/> ls //habitatThis yields:Bactrian camels' habitat consists mainly of Asia's deserts.The temperature ranges from -29 degrees Celsius inthe winter to 38 degrees Celsius in the summer.Dromedary camels prefer desert conditions characterized bya long dry season and a short rainy season.Introduction of the dromedary into other climates hasproven unsuccessful as the camel is sensitive to thecold and humidity (Nowak 1991).Llamas are found in deserts, mountainous areas, andgrasslands.Guanacos inhabit grasslands and shrublands from sealevel to 4,000m. Occasionally they winter in forests.Vicunas are found in semiarid rolling grasslands andplains at altitudes of 3,500-5,750 meters. These landsare covered with short and tough vegetation. Due totheir daily water demands, vicunas live in areas wherewater is readily accessible. Climate in the habitat isusually dry and cold. Nowak (1991), Grizmek (1990).Found 5 node(s).xsh cams:/>Or, if we want our query to be more specific, we can use predicateexpressions in our XPath statement. For example,xsh cams:/> ls //habitat[ancestor::species/@name='Lama guanicoe']to select just the Guanaco's habitat element.Similarly, we can change the command evaluation context within the currentdocument by giving an XPath expression to the cd command:xsh cams:/> cd //species[@name='Camelus dromedarius']/natural-historyxsh cams:/camelids/species[2]/natural-history>Which causes the context location in our shell prompt to change to reflectthe new context to which we have navigated. Thus, commands not explicitlypassed an absolute location path will be evaluated in the context of the element contained in the document'ssecond element (the one whose nameattribute is equal to "Camelus dromedarius"). Thus, if we give thels commadn with no path specified, we'll see the contents of thenew context:xsh cams:/camelids/species[2]/natural-history> ls............Found 1 node(s).xsh cams:/camelids/species[2]/natural-history>In addition, xsh provides a way to execute commands on anycurrently open document without changing the element context by prependingthat document's ID and a colon to the XPath expression:xsh cams:/camelids/species[2]/natural-history> cd /xsh cams:/> open xmlnews=http://www.xml.com/xml/news.rssparsing http://www.xml.com/xml/news.rssdone.xsh xmlnews:/>xsh xmlnews:/> ls cams:/camelids/species[3]/common-nameLlamaFound 1 node(s).xsh xmlnews:/>Notice that the context changed to the root of the newly opened RSSdocument once it is parsed into memory, but we still have easy access to thedata contained in the camelids document by adding that document's ID(cams) and a colon to the front of the path.Also note that the location of the file passed to the opencommand is not limited to files on the local machine; it can also be an HTTPor FTP URL, so long as a well-formed XML document is returned.To see a list of all the currently open documents and their associatedIDs, use the files command:xsh xmlnews:/> filescams = files/camelids.xmlxmlnews = http://www.xml.com/xml/news.rssxsh xmlnews:/>Closing an open document is as easy as passing its ID to theclose command.xsh xmlnews:/> close xmlnewsclosing file http://www.xml.com/xml/news.rssxsh :>If we wanted to save a local copy of the xmlnews documentbefore closing, we would use the saveas command:.xsh xmlnews:/> saveas xmlnews files/xmldotcom_news.rssxmlnews=new_document1.xml --> files/xmldotcom_news.rss (utf-8)saved xmlnews=files/xmldotcom_news.rss as files/xmldotcom_news.rss in utf-8 encodingxsh :>We've now reviewed xsh basics: we can start the shell, open,close, and navigate through contents of XML documents. If this is all therewas to xsh, it would still be a winner as an XPath testbed andteaching tool (making it quite useful to users of XSLT and XPathScript, aswell as XML::LibXML and the other Perl modules which offer anXPath interface). But xsh bills itself as an XMLediting shell, and as we will see, it's that and a fair bit more.Pages: 1, 2Next Page
Tagged Articles
Post to del.icio.us
This article has been tagged:
xml Articles that share the tag xml:Very Dynamic Web Interfaces (595 tags)Introducing del.icio.us (181 tags)How to Create a REST Protocol (161 tags)Secure RSS Syndication (112 tags)XML on the Web Has Failed (109 tags)View Allxpath Articles that share the tag xpath:Parsing an XML Document with XPath (74 tags)Top Ten Tips to Using XPath and XPointer (8 tags)The XPath 2.0 Data Model (7 tags)What Is XSLT (7 tags)The Path of Control (5 tags)View Allperl Articles that share the tag perl:Programming is Hard, Let's Go Scripting... (177 tags)Using Ajax from Perl (101 tags)Ten Essential Development Practices (97 tags)Everyday Perl 6 (92 tags)Catalyst (91 tags)View Allshell Articles that share the tag shell:Top Ten Mac OS X Tips for Unix Geeks (24 tags)bash on Mac OS X (7 tags)Network Your Shell Scripts with Netpipes (6 tags)Enhanced Interactive Python with IPython (5 tags)Top Ten Data Crunching Tips and Tricks (5 tags)View AllSponsored ResourcesInside LightroomContact Us | Our Mission | Privacy Policy | Advertise With Us | | Submissions GuidelinesCopyright © 2008O'Reilly Media, Inc. | (707) 827-7000 / (800) 998-9938 разделы
управление ярославль
позитивный психология
герб рф
органический растворитель
кострома риелтор
профиль salamander
trinity hi-fi
mastercard
shell