Merge pull request #444 from Asheara/master

Introduction to XPath
This commit is contained in:
Eugen 2016-06-08 22:31:29 +01:00
commit 144397849d
6 changed files with 480 additions and 1 deletions

View File

@ -66,7 +66,7 @@
<module>spring-thymeleaf</module> <module>spring-thymeleaf</module>
<module>spring-zuul</module> <module>spring-zuul</module>
<module>jsf</module> <module>jsf</module>
<module>xml</module>
</modules> </modules>
</project> </project>

139
xml/pom.xml Normal file
View File

@ -0,0 +1,139 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>xml</artifactId>
<version>0.1-SNAPSHOT</version>
<name>xml</name>
<dependencies>
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>xml</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</build>
<properties>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<!-- marshalling -->
<jackson.version>2.7.2</jackson.version>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
</properties>
</project>

View File

@ -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;
}
}

View 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);
}
}

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>

View File

@ -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>