This page is dedicated to a discussion on using the Perl module XML::XPath to read and write XML documents.

Links on this page:

Reading an XML document with only elements using XML::XPath
Reading an XML file with elements and one attribute using XML::XPath
Creating an XML file with all elements
A program that creates an XML file with elements and one attribute.
A Perl program that reads a text file and outputs an XML file
Read an XML file and checks whether an attribute of condition is "fair" and removes the element.
Add a book to an existing XML document.
Checking whether a file is a valid XML document.

 

Reading an XML document with only elements using XML::XPath

Below is the code for GetBookValuesXML_XPath_1.pl which may be loaded from here. It reads the XML document called Book1.xml which consists only of node elements (no attributes). A very important point is that the double slash (//) on line 5 in front of 'book' allows the parser to skip over the <top> root element and go directly to the <book> element.

GetBookValuesXML_XPath.jpg

Back to top

Reading an XML file with elements and one attribute (Book2.xml) using XML::XPath is the program GetBookValuesXML_XPath_2.pl which may be loaded from here.

GetBookValuesXML_XPath_2.jpg

Back to top.

Creating an XML file with all elements - one book - with name "MakeBookXML_XPath_1.pl" may be loaded from here.

MakeBookXML_XPath_1_1.mpg
MakeBookFileXML_XPath_1_2.jpg

Back to top.

Here we have a program that creates an XML file with elements and one attribute. It is called MakeBookXML_XPath_2.pl.

MakeBookXML_XPath_2_1.jpg
MakeBookXML_XPath_2_2.jpg

Back to top.

Here is the next Perl program that reads a text file and outputs an XML file. The Perl program is called ReadBookFileAndCreateXML_XPath.pl.

ReadBookFileAndCreateXML_XPath_1.jpg
MakeBookFileUsingXML_XPath_2.jpg
ReadTextFileAndCreateXML_XPath_3.jpg

Back to top.

Here is a program that detects whether an attribute of condition is "fair" and removes the element. The name of the program is RemoveNodeXML_XPath.pl.

RemoveNodeXML_XPath_1.jpg
RemoveNodeXML_XPath_2.jpg

Back to top

Here is a program called AddABookXML_XPath.pl which adds a book to an existing XML document.

AddABookXML_XPath_1.jpg
AddABookXML_XPath_2.jpg
AddABookXML_XPath_3.jpg

Back to top.

Before you load an XML file, you should check whether it is a valid XML document:

ValidXML_XPathFile.jpg

Back to top.