Introduction to XPath

This commit is contained in:
Raquel Garrido Crespo
2016-06-08 23:13:45 +02:00
parent 9be037e24f
commit a156fa8590
6 changed files with 480 additions and 1 deletions
@@ -0,0 +1,193 @@
package com.baeldung.xml;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DefaultParser {
private File file;
public DefaultParser(File file) {
this.file = file;
}
public NodeList getFirstLevelNodeList() {
NodeList nodeList = null;
try {
FileInputStream fileIS = new FileInputStream(this.getFile());
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(fileIS);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/Tutorials/Tutorial";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
} catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException e) {
e.printStackTrace();
}
return nodeList;
}
public Node getNodeById(String id) {
Node node = null;
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(this.getFile());
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/Tutorials/Tutorial[@tutId=" + "'" + id + "'" + "]";
node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
} catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException e) {
e.printStackTrace();
}
return node;
}
public NodeList getNodeListByTitle(String name) {
NodeList nodeList = null;
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(this.getFile());
this.clean(xmlDocument);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//Tutorial[descendant::title[text()=" + "'" + name + "'" + "]]";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
} catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException e) {
e.printStackTrace();
}
return nodeList;
}
public NodeList getElementsByDate(String date) {
NodeList nodeList = null;
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(this.getFile());
this.clean(xmlDocument);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//Tutorial[number(translate(date, '/', '')) > " + date + "]";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
} catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException e) {
e.printStackTrace();
}
return nodeList;
}
public NodeList getAllTutorials() {
NodeList nodeList = null;
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(this.getFile());
this.clean(xmlDocument);
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setNamespaceContext(new NamespaceContext() {
@Override
public Iterator getPrefixes(String arg0) {
return null;
}
@Override
public String getPrefix(String arg0) {
return null;
}
@Override
public String getNamespaceURI(String arg0) {
if ("bdn".equals(arg0)) {
return "http://www.baeldung.com/full_archive";
}
return null;
}
});
String expression = "/bdn:Tutorials/bdn:Tutorial";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
} catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException e) {
e.printStackTrace();
}
return nodeList;
}
private void clean(Node node) {
NodeList childs = node.getChildNodes();
for (int n = childs.getLength() - 1; n >= 0; n--) {
Node child = childs.item(n);
short nodeType = child.getNodeType();
if (nodeType == Node.ELEMENT_NODE)
clean(child);
else if (nodeType == Node.TEXT_NODE) {
String trimmedNodeVal = child.getNodeValue().trim();
if (trimmedNodeVal.length() == 0)
node.removeChild(child);
else
child.setNodeValue(trimmedNodeVal);
} else if (nodeType == Node.COMMENT_NODE)
node.removeChild(child);
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
@@ -0,0 +1,83 @@
package com.baeldung.xml;
import static org.junit.Assert.*;
import java.io.File;
import org.junit.Test;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Unit test for simple App.
*/
public class DefaultParserTest {
final String fileName = "src/test/resources/example.xml";
final String fileNameSpace = "src/test/resources/example_namespace.xml";
DefaultParser parser;
@Test
public void getFirstLevelNodeListTest() {
parser = new DefaultParser(new File(fileName));
NodeList list = parser.getFirstLevelNodeList();
assertNotNull(list);
assertTrue(list.getLength() == 4);
}
@Test
public void getNodeListByTitle() {
parser = new DefaultParser(new File(fileName));
NodeList list = parser.getNodeListByTitle("XML");
for (int i = 0; null != list && i < list.getLength(); i++) {
Node nod = list.item(i);
assertEquals("java", nod.getAttributes().getNamedItem("type").getTextContent());
assertEquals("02", nod.getAttributes().getNamedItem("tutId").getTextContent());
assertEquals("XML", nod.getFirstChild().getTextContent());
assertEquals("title", nod.getFirstChild().getNodeName());
assertEquals("description", nod.getChildNodes().item(1).getNodeName());
assertEquals("Introduction to XPath", nod.getChildNodes().item(1).getTextContent());
assertEquals("author", nod.getLastChild().getNodeName());
assertEquals("XMLAuthor", nod.getLastChild().getTextContent());
}
}
@Test
public void getNodeById() {
parser = new DefaultParser(new File(fileName));
Node node = parser.getNodeById("03");
String type = node.getAttributes().getNamedItem("type").getNodeValue();
assertEquals("android", type);
}
@Test
public void getNodeListByDate(){
parser = new DefaultParser(new File(fileName));
NodeList list = parser.getNodeListByTitle("04022016");
for (int i = 0; null != list && i < list.getLength(); i++) {
Node nod = list.item(i);
assertEquals("java", nod.getAttributes().getNamedItem("type").getTextContent());
assertEquals("04", nod.getAttributes().getNamedItem("tutId").getTextContent());
assertEquals("Spring", nod.getFirstChild().getTextContent());
assertEquals("title", nod.getFirstChild().getNodeName());
assertEquals("description", nod.getChildNodes().item(1).getNodeName());
assertEquals("Introduction to Spring", nod.getChildNodes().item(1).getTextContent());
assertEquals("author", nod.getLastChild().getNodeName());
assertEquals("SpringAuthor", nod.getLastChild().getTextContent());
}
}
@Test
public void getNodeListWithNamespace(){
parser = new DefaultParser(new File(fileNameSpace));
NodeList list = parser.getAllTutorials();
assertNotNull(list);
assertTrue(list.getLength() == 4);
}
}
+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0"?>
<Tutorials>
<Tutorial tutId="01" type="java">
<title>Guava</title>
<description>Introduction to Guava</description>
<date>04/04/2016</date>
<author>GuavaAuthor</author>
</Tutorial>
<Tutorial tutId="02" type="java">
<title>XML</title>
<description>Introduction to XPath</description>
<date>04/05/2016</date>
<author>XMLAuthor</author>
</Tutorial>
<Tutorial tutId="03" type="android">
<title>Android</title>
<description>Introduction to Android</description>
<date>04/03/2016</date>
<author>AndroidAuthor</author>
</Tutorial>
<Tutorial tutId="04" type="java">
<title>Spring</title>
<description>Introduction to Spring</description>
<date>04/02/2016</date>
<author>SpringAuthor</author>
<sections>
<section name="core">Spring Core</section>
<section name="mvc">Spring MVC</section>
<section name="batch">Spring Batch</section>
</sections>
</Tutorial>
</Tutorials>
@@ -0,0 +1,32 @@
<?xml version="1.0"?>
<Tutorials xmlns="http://www.baeldung.com/full_archive">
<Tutorial tutId="01" type="java">
<title>Guava</title>
<description>Introduction to Guava</description>
<date>04/04/2016</date>
<author>GuavaAuthor</author>
</Tutorial>
<Tutorial tutId="02" type="java">
<title>XML</title>
<description>Introduction to XPath</description>
<date>04/05/2016</date>
<author>XMLAuthor</author>
</Tutorial>
<Tutorial tutId="03" type="android">
<title>Android</title>
<description>Introduction to Android</description>
<date>04/03/2016</date>
<author>AndroidAuthor</author>
</Tutorial>
<Tutorial tutId="04" type="java">
<title>Spring</title>
<description>Introduction to Spring</description>
<date>04/02/2016</date>
<author>SpringAuthor</author>
<sections>
<section name="core">Spring Core</section>
<section name="mvc">Spring MVC</section>
<section name="batch">Spring Batch</section>
</sections>
</Tutorial>
</Tutorials>