Escolar Documentos
Profissional Documentos
Cultura Documentos
XLPATH:
UMA LINGUAGEM PARA NAVEGAÇÃO EM LINKS XML
SALVADOR
2010
MARCELO MENDONÇA DOS SANTOS
XLPATH:
Uma Linguagem Para Navegação em Links XML
SALVADOR
2010
MARCELO MENDONÇA DOS SANTOS
XLPATH:
BANCA EXAMINADORA
1. INTRODUÇÃO ................................................................................................... 12
2. CONTEXTUALIZAÇÃO ..................................................................................... 15
5. CONCLUSÃO ..................................................................................................... 52
REFERÊNCIAS......................................................................................................... 53
1. INTRODUÇÃO
1.1. MOTIVAÇÃO
dentre outras, que estão presentes também em SQL. Além de XQuery, o W3C
desenvolveu XPath (XML Path Language) [22], uma linguagem path que, assim
como a primeira, permite a manipulação de dados estruturados em XML, porém com
o diferencial de oferecer mecanismos mais simplificados.
1.2. OBJETIVOS
2. CONTEXTUALIZAÇÃO
2.1. XLINK
outbound, e pode ser declarado através de qualquer elemento XML que contenha o
atributo type, do namespace XLink, com o valor “simple”. O código seguinte
representa um link simples: <book xlink:type=”simple” xlink:href=”...”>Book’s
Name</book>.
Outra particularidade dos links estendidos é que estes podem ter uma
estrutura bastante complexa, sendo possível que determinados elementos sejam
declarados como seus filhos diretos, desempenhando alguns papéis, que incluem:
(ii) Elementos do tipo arco (arc), que provêem regras de travessia entre os
recursos participantes no link;
<bibliotecaLink xlink:type="extended">
<livro xlink:href="livros.xml#oBanquete"
xlink:label="livro01" xlink:type="locator "
xlink:title=”O Banquete” />
<livro xlink:href="livros.xml#retorica"
xlink:label="livro02" xlink:type="locator”
xlink:title=”Retórica” />
<autor xlink:href="autores.xml#platao"
xlink:label="autor01” xlink:type="locator"
xlink:title=”Platão” />
<autor xlink:href="autores.xml#aristoteles"
xlink:label="autor02" xlink:type="locator"
xlink:title=”Aristóteles” />
<go xlink:type="arc" xlink:from="autor01"
xlink:to="livro01" xlink:title="Livro publicado"
xlink:arcrole=”http://www.exemplo.br/autor-livro” />
<go xlink:type="arc" xlink:from="autor02"
xlink:to="livro02" xlink:title="Livro publicado"
xlink:arcrole=”http://www.exemplo.br/autor-livro” />
<go xlink:type="arc" xlink:from="livro01"
xlink:to="autor01" xlink:title="Autor do livro"
xlink:arcrole=”http://www.exemplo.br/livro-autor” />
</bibliotecaLink>
Outra característica importante de XLink são seus atributos globais, que são
aqueles que utilizam o namespace de XLink. Eles podem ser classificados segundo
a finalidade, conforme abaixo:
Tipos de Elementos
type R R R R R R
title O O O O O --------
2.2. XPATH
XML provê um meio para descrever dados através de uma rica, flexível e
eficiente estrutura de marcação, que fornece metadados encapsulados em etiquetas
20
<livraria>
<livro categoria=”filosofia”>
<titulo lang=”pt”>A República</titulo>
<autor>Platão</autor>
<ano>2005</ano>
<preco>24.90</preco>
</livro>
</livraria>
21
Root element:
<livraria>
Parent
Child
Attribute: Element: Attribute:
lang <livro> categoria
Siblings
Text: Text: Text: Text:
A República Platão 2005 24.90
expressão for verdadeira para um dado nó, então o mesmo é mantido na lista. Caso
contrário, o nó é deletado [6].
Eixo Descrição
XPath provê algumas funções que podem ser utilizadas em predicados, como
por exemplo a função last( ), que retorna o número de nós de uma lista, e position( ),
cujo resultado é a posição do nó que está sendo testado. Além disso, predicados
também podem conter alguns operadores, tais como aritméticos, comparativos,
dentre outros.
Tabela 3. Especificação de Nó em XPath
Especificação Descrição
Root element:
<livraria>
Element:
<livro>
Attribute: Attribute:
lang categoria
/descendant::livro[ano=’2005’]/ano
Figura 3. Mecanismos de XPath
24
2.3. XSPATH
Como alternativa, Cavalieri et al. [2] propõem XSPath, uma linguagem que
deriva de XPath, porém com foco em consultas sobre documentos XML Schema.
Em XSPath, a noção de consultas realizadas em passos é estendida para permitir a
25
navegação através das ligações entre os tipos dos elementos contidos no esquema,
inclusive dentro da estrutura hierárquica dos tipos complexos [14].
/HL::child::element(mail)/HL::child::element(attachment)
i {23}
/HL::child::element(picture)/
ii /HL::child::type(envelopeType)/HL::child::attribute(header) {18}
iv /HL::descendant-or-self::type()[restriction(pattern)] {27}
/HL::child::element(mail)/HL::child::element(attachment)
v {22}
/LL::child::operator(sequence)/LL::child::operator(choice)
2.4. XPATH+
podem aparecer tanto nas instâncias, como nos esquemas, ou ainda agrupados em
linkbases, formando redes de links.
Quanto à semântica, o eixo link-source seleciona uma lista de nós que têm o
nó de contexto como recurso de origem, enquanto o link-destination executa a
operação inversa, ou seja, seleciona uma lista de nós que têm o nó de contexto
como recurso de destino.
2.5 CONCLUSÃO
Este capítulo apresenta a linguagem XLPath, que tem por objetivo permitir
consultas sobre links em documentos XML. Inicialmente, são levantados os
requisitos para essa linguagem. Em seguida, uma formalização para a mesma é
definida e são apontadas as premissas que baseiam suas abordagens, a partir de
uma representação gráfica desenvolvida para os links. Os detalhes sintáticos e
semânticos são discutidos em seção posterior. Finalmente, propõe-se uma
arquitetura para um processador de expressões XLPath.
Definição 3 (função eixo): Seja d um documento XML (T, β, λ, Rχ, Rσ). Para
uma relação de eixo XLPath χ ⊆ Rχ e ρ(β) como o potencial conjunto de β, define-se
a função fχ: ρ(β)→ P(β) (e então sobrecarrega-se o nome da relação χ, como por
exemplo fchild), com fχ(X) = {y ∈ β | ∃x ∈ X, tal que (x,y) ∈ χ}.
33
Definição 4: Sendo d´ e d´´ dois documentos XML (T´, β´, λ´, Rχ´, Rσ´) e (T´´,
β´´, λ´´, Rχ´´, Rσ´´), respectivamente. Para uma relação XLPath σ ⊆ Rσ´ em d´, é
definida a função gσ : P(β´)→ P(β´´) com gσ(X) = {y ∈ β´´ | ∃x ∈ X, tal que (x,y) ∈ σ}.
ϕ = {(σ(xi) |χ(i)}
function NavgationPath(ϕ, nodeList)
begin
if ϕ is xpathExpression then
return xpathParser(ϕ, nodeList)
else
return xlpathParser(ϕ, nodeList)
endif
end
O Quadro 5 traz um link estendido que representa uma grade curricular onde
há exemplos de todos os itens citados: três recursos, sendo um local e dois remotos
(com seus respectivos locators), dois arcos e um título. Além disso, cada elemento
possui diversos atributos.
35
<gradeCurricular
xmlns:xlink=”http://www.w3.org/1999/xlink”
xlink:type=”extended”>
<titulo
xlink:type=”title”>Grade Curricular de Aristóteles</titulo>
<aluno
xlink:type=”locator”
xlink:href=” http://www.exemplo.com/alunos#aristoteles”
xlink:label=”aluno15”
xlink:title=”Aristóteles”/>
<curso
xlink:type=”locator”
xlink:href=” http://www.exemplo.com/cursos#hf-02”
xlink:label=”curso02”
xlink:title=”História da Filosofia II”/>
<cr
xlink:type=”resource”
xlink:label=”aluno15CR”>7.0</cr>
<go
xlink:type=”arc”
xlink:from=”aluno15”
xlink:to=”aluno15CR”
xlink:title=”Coeficiente de Rendimento de Aristóteles”/>
<go
xlink:type=”arc”
xlink:from=”curso02”
xlink:to=”aluno15”
xlink:arcrole=”http://www.exemplo.com/arcrole/matriculado”
xlink:title=”Aristóteles matriculado no curso”/>
</ gradeCurricular >
Linkbase Instância
gradeCurricular
href
to from
go1 href
aristoteles
aluno15CR
aluno15
to
href
go2
href
titulo curso02
hf-02
from
href
Para que isso seja possível, XLPath provê uma abordagem em alto nível,
onde o referenciamento por meio de locators é abstraído, e os arcos passam a
37
Linkbase Instância
to
gradeCurricular
from
to aristoteles
go1
aluno15CR to
to
titulo go2
hf-02
from
from
Com base nisso, para manter a consistência sintática sem prejuízo semântico,
XLPath provê uma abordagem para links simples a partir de seus equivalentes
estendidos. Em outras palavras, no momento do processamento de uma consulta, o
processador XLPath assimila os links simples como sendo seus equivalentes
estendidos, permitindo dessa forma que a consulta alcance os componentes destes
links a partir da mesma sintaxe utilizada para os links estendidos. O Quadro 6
38
<alunoLink
xmlns:xlink=”http://www.w3.org/1999/xlink”
xlink:type=”extended”>
<resource
xlink:type=”resource”
xlink:label=”local”>Aristóteles</resource>
<locator
xlink:type=”locator”
xlink:href=”…”
xlink:label=”remote”/>
<go
xlink:type=”arc”
xlink:from=”local”
xlink:to=”remote”/>
</ alunoLink >
hf-02 LL::arc-source
titulo HL::arc-destination
A seleção efetuada por um eixo não leva em conta o tipo do elemento que
está referenciando ou sendo referenciado pelo nó de contexto, mas apenas se há ou
não um referenciamento. Além disso, ainda que os elementos selecionados sejam
42
todos do mesmo tipo, dispondo apenas dos eixos não é possível diferenciá-los
segundo algum critério.
3.6.3. Predicado
Em situações como esta, para se refinar ainda mais uma consulta, XLPath
provê a opção de se aplicar um predicado, que consiste em um operador para testar
características do nó de contexto, como atributos, conteúdo texto, ou o nome do link
do qual ele faz parte. O operador é testado em cada nó resultante da especificação
de elemento como uma função booleana: quando o resultado é verdadeiro, o nó é
43
aluno15 aluno15
locator(aluno15)
curso02
go1 go1
arc(go)
go2 go2
aristoteles
resource() aluno15CR
aluno15CR
aristoteles
remote() aristoteles
aluno15CR
aluno15CR aluno15CR
go2 element() go2
aluno15 aluno15
Nó de Nós
Especificação de elemento com Predicado
Contexto identificados
go1
2
arc(go)[attribute(from)=”aluno15”] go1
go
go1 arc(go)[attribute(arcrole)=
2
go2
go ”http://www.exemplo.com/arcrole/matriculado”]
aluno15CR
go2 element()[text()=”7.0”] aluno15CR
aluno15
aluno15
curso02 aluno15
locator()[link(gradeCurricular)]
locator1 curso02
locator2
level::axis::element(elementName*)[operator(operatorName*)=”operatorValue”]*
Element
Formatter Processor Store
DOM
Result
Console Executor Expression Step
Query
and
Document View Controller Model
s
Figura 7. Arquitetura de um Processador XLPath
3.8. CONCLUSÃO
4. ESTUDO DE CASO
Por conta disso, para a realização dos testes foi utilizado o documento
escola_de_filosofia.xml, que contém o link Grade Curricular apresentado no Quadro
5. Além deste, esse documento é composto por outro link estendido de mesmo
nome. Os recursos remotos (nesse caso, elementos XML representando indivíduos
e cursos acadêmicos) referenciados por esses links também se encontram neste
mesmo documento.
Locators = {aluno}
Arcs = {}
Resources = {}
Remotes = {}
Locators = {}
Arcs = {go}
Resources = {}
Remotes = {}
Locators = {}
Arcs = {}
Resources = {}
Remotes = {historiaFilosofia2}
Locators = {}
Arcs = {go, go}
Resources = {}
Remotes = {}
Locators = {}
Arcs = {}
Resources = {}
Remotes = {platao}
Locators = {}
Arcs = {go}
Resources = {}
Remotes = {}
50
Locators = {}
Arcs = {}
Resources = {}
Remotes = {introducaoFilosofia}
Locators = {}
Arcs = {go, go}
Resources = {}
Remotes = {}
Locators = {}
Arcs = {}
Resources = {}
Remotes = {socrates}
4.2. CONCLUSÃO
• Apêndice A, escola_de_filosofia.xml;
• Apêndice B, XLPathConsole.java;
• Apêndice C, XLPathFormatter.java;
• Apêndice D, XLPathExpression.java;
• Apêndice E, XLPathStep.java;
• Apêndice F, XLPathElementStore.java;
• Apêndice G, XLPathExecutor.java;
• Apêndice H, XLPathProcessor.java.
5. CONCLUSÃO
REFERÊNCIAS
[3] COVER, Robin. SGML: general introductions and overviews. Disponível em:
<http://xml.coverpages.org/general.html>. Acesso em: junho 2010.
[4] DEITEL, Harvey M. et al. XML: how to program. New Jersey: Prentice Hall,
2000. 934 p.
[5] GARSHOL, Lars Marius. BNF and EBNF: what are they and how do they
work?. Disponível em: <http://www.garshol.priv.no/download/text/bnf.html>.
Acesso em: junho 2010.
[7] LIBKIN, Leonid. Logics For Unrankered Trees: an overview. Logical Methods
in Computer Science 2, 2006.
[8] LOWE, David; WILDE, Erik. Improving Web Linking Using XLink. Sydney:
University of Technology, 2001.
[10] SILVA, P. C., TIMES, V. C. XPath+: a tool for linked XML documents
navigation. Lyon: XSym 2009 - Sixth International XML Database Symposium,
2009.
[17] W3C. Extensible Markup Language (XML) 1.0 (Fifith Edition). W3C
Recommendation (2008). Disponível em: <http://www.w3.org/TR/REC-xml/>.
Acesso em: junho 2010.
[20] W3C. World Wide Web Consortium: about W3C. Disponível em:
<http://www.w3.org/Consortium/ >. Acesso em: junho 2010.
[21] W3C. XML Linking Language (XLink) Version 1.0. W3C Recommendation
(2001). Disponível em: <http://www.w3.org/TR/xlink/>. Acesso em: junho 2010.
[22] W3C. XML Path Language (XPath) Version 1.0. W3C Recommendation
(1999). Disponível em: <http://www.w3.org/TR/xpath/>. Acesso em: junho
2010.
[23] W3C. XML Pointer Language (XPointer) Version 1.0. W3C Last Call
Working Draft (2001). Disponível em: <http://www.w3.org/TR/2001/WD-xptr-
20010108/>. Acesso em: junho 2010.
[24] W3C. XML Schema Part 1: structures second edition. W3C Recommendation
(2004). Disponível em: <http://www.w3.org/TR/xmlschema-1/>. Acesso em:
junho 2010.
[25] W3C. XQuery 1.0: an XML query language. W3C Recommendation (2007).
Disponível em: <http://www.w3.org/TR/xquery/>. Acesso em: junho 2010.
APÊNDICE A – escola_de_filosofia.xml
<platao id="platao">
<idade>52</idade>
<matricula>456</matricula>
</platao>
<socrates id="socrates">
<idade>64</idade>
<matricula>789</matricula>
</socrates>
<historiaFilosofia2 id="hf-02">
<horas>80</horas>
</historiaFilosofia2>
<introducaoFilosofia id="if">
<horas>75</horas>
</introducaoFilosofia>
<gradeCurricular xmlns:xlink="http://www.w3.org/1999/xlink"
xlink:type="extended">
<titulo xlink:type="title">Grade Curricular de Aristóteles</titulo>
xlink:arcrole="http://www.exemplo.com/arcrole/matriculado"
xlink:title="Aristóteles matriculado no curso"
xlink:role="matricula" />
<gradeCurricular xmlns:xlink="http://www.w3.org/1999/xlink"
xlink:type="extended">
<titulo xlink:type="title">Grade Curricular de Platão</titulo>
APÊNDICE B - XLPathConsole.java
package xlpath.view;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;
import xlpath.controller.XLPathExecutor;
import xlpath.model.XLPathExpression;
public XLPathConsole(){
try {
makeWindow();
58
} catch (Exception e) {
e.printStackTrace();
}
}
lExpression.setText("Expression: ");
lExpression.setBounds(new Rectangle(20, 20, 200, 20));
lExpression.setFont(new Font("Dialog", 1, 11));
lFile.setText("File: ");
lFile.setBounds(new Rectangle(480, 20, 150, 20));
lFile.setFont(new Font("Dialog", 1, 11));
bFile.setText("...");
bFile.setBounds(new Rectangle(685, 40, 20, 20));
bFile.setFont(new Font("Dialog", 1, 11));
bFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
chooseFile(ae);
}
59
});
bSubmit.setText("Enviar");
bSubmit.setBounds(new Rectangle(740, 40, 80, 20));
bSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
execute(ae);
}
});
spResult.setBounds(new Rectangle(20, 75, 800, 360));
spResult.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
tResult.setEditable(false);
tResult.setWrapStyleWord(true);
tResult.setLineWrap(true);
String inicialMessage = "XLPath Query Processor - Versão 1.0\n\nInstruções:\n\n" +
"(1) - Insira uma expressão XLPath\n" +
"(2) - Selecione um arquivo XML\n" +
"(3) - Clique 'Enviar'" +
"\n\n\nLimitações:\n\n" +
"Esta versão não suporta navegação em múltiplos
documentos." +
"\n\n\nDesenvolvido por:\n\n" +
"Marcelo Mendonça -
mendonca.area1@gmail.com\n" +
"Jader do Monte -
jader_do_monte@hotmail.com";
tResult.setText(inicialMessage);
spResult.getViewport().add(tResult, null);
this.getContentPane().add(lNameApp, null);
this.getContentPane().add(jExpression, null);
this.getContentPane().add(lExpression, null);
this.getContentPane().add(lFile, null);
this.getContentPane().add(jFile, null);
this.getContentPane().add(bSubmit, null);
this.getContentPane().add(spResult, null);
this.getContentPane().add(bFile, null);
}
if(returnVal == JFileChooser.APPROVE_OPTION){
File file = jTreeFile.getSelectedFile();
60
jFile.setText(file.getAbsolutePath());
}
}
}else{
tResult.setText("Por favor, selecione um arquivo valido.");
}
}else{
tResult.setText("Por favor, informe uma expressao XLPath.");
}
}
APÊNDICE C - XLPathFormatter.java
package xlpath.view;
import java.util.List;
import xlpath.model.XLPathElementStore;
if(j<resultByStep.get(i).getResources().size()-1){
formatted += ", ";
}
}
}
formatted += "}\nRemotes = {";
if(resultByStep.get(i).getRemotes()!=null){
for(int j=0; j<resultByStep.get(i).getRemotes().size(); j++){
formatted +=
resultByStep.get(i).getRemotes().get(j).getNodeName();
if(j<resultByStep.get(i).getRemotes().size()-1){
formatted += ", ";
}
}
}
formatted += "}\n\n";
}
}else{
formatted = "Erro! Consulta nao pode ser processada...";
}
return formatted;
}
APÊNDICE D - XLPathExpression.java
package xlpath.model;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
//Método Construtor
public XLPathExpression(String expression){
this.expression = expression;
}
while(st.hasMoreTokens()){
XLPathStep step = new XLPathStep("/"+st.nextToken());
this.stepStrings.add(step.getStepString());
if(step.validate()){System.out.println("validou(Step)");
this.steps.add(step);
}else{System.out.println("nao validou(Step)");
validity = false;
}
}
return validity;
}
}
65
APÊNDICE E - XLPathStep.java
package xlpath.model;
//Método Construtor
public XLPathStep(String stepString){
if(stepString.length()>=18){
this.stepString = stepString;
int indexIn = 0;
int indexFim = 0;
indexFim = stepString.indexOf("::");
if(indexFim>indexIn){
//Pega a primeira palavra da expressão
String firstWord = stepString.substring(indexIn+1, indexFim);
indexIn = indexFim + 1;
indexFim = stepString.indexOf("::", indexIn);
66
if(indexFim>indexIn){
this.level = stepString.substring(indexIn + 1,
indexFim);
}
}
indexIn = indexFim;
indexFim = stepString.indexOf(")", indexIn);
if(indexFim>indexIn){
if(stepString.substring(indexIn+1,
indexFim).length() != 0){
this.elementName =
stepString.substring(indexIn + 1, indexFim).replace("'", "");
}
indexIn = indexFim;
indexIn = indexFim;
if(stepString.indexOf(")", indexIn) != -
1){
indexFim =
stepString.indexOf(")", indexIn);
if(stepString.substring(indexIn
+ 1, indexFim).equals("")){
this.attributeName =
"";
}else{
this.attributeName =
stepString.substring(indexIn + 1, indexFim).replace("'", "");
}
}
67
indexIn = stepString.indexOf("=");
indexFim = stepString.indexOf("]",
indexIn);
if(indexIn != -1){
this.attributeValue =
stepString.substring(indexIn + 1, indexFim).replace("'", "");
}else{
this.attributeValue = "";
}
}
}
}
}
}
}
}
||this.level.equals("HL"))){
validity = false;
}
if(!(this.axis.equals("linked")
||this.axis.equals("arc-source")
||this.axis.equals("arc-destination"))){
validity = false;
}
if(!(this.elementSpec.equals("arc")
||this.elementSpec.equals("locator")
||this.elementSpec.equals("remote")
||this.elementSpec.equals("resource")
||this.elementSpec.equals("element"))){
validity = false;
}
if(!(this.attributeSpec.equals("attribute")||this.attributeSpec.equals(""))){
validity = false;
}
return validity;
}
}
70
APÊNDICE F - XLPathElementStore.java
package xlpath.model;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Element;
public XLPathElementStore(){
}
public void storeElement(Element element){
if((element.getNodeType()==1)&&(!isRegistered(element))){
if(element.hasAttribute("xlink:type")){
if(element.getAttribute("xlink:type").equals("arc")){
this.elements.add(element);
this.arcs.add(element);
register(element);
}else if(element.getAttribute("xlink:type").equals("locator")){
this.elements.add(element);
this.locators.add(element);
register(element);
}else if(element.getAttribute("xlink:type").equals("resource")){
this.elements.add(element);
this.resources.add(element);
register(element);
}
}else if(element.hasAttribute("id")){
this.elements.add(element);
this.remotes.add(element);
register(element);
}
}
}
71
if((element.getParentNode()!=null)&&(element.hasAttribute("xlink:from"))
&&(element.hasAttribute("xlink:to"))){
elementString += element.getParentNode().getNodeName();
elementString += element.getNodeName();
elementString += type;
elementString += element.getAttribute("xlink:from");
elementString += element.getAttribute("xlink:to");
}
}else if(type.equals("locator")){
if((element.getParentNode()!=null)&&(element.hasAttribute("xlink:label"))){
elementString +=
element.getParentNode().getNodeName();
elementString += element.getNodeName();
elementString += type;
elementString += element.getAttribute("xlink:label");
}
}else if(type.equals("resource")){
if((element.getParentNode()!=null)&&(element.hasAttribute("xlink:label"))){
elementString += element.getParentNode().getNodeName();
elementString += element.getNodeName();
elementString += type;
elementString += element.getAttribute("xlink:label");
}
}
}else if((element.hasAttribute("id"))){
elementString += element.getNodeName();
elementString += "remote";
72
elementString += element.getAttribute("id");
}
return elementString;
}
APÊNDICE G - XLPathExecutor.java
package xlpath.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import xlpath.model.XLPathElementStore;
import xlpath.model.XLPathExpression;
}
}
}
if((element.getAttribute("id")!=null)&&(element.getAttribute("id").equals(startElementId))){
return element;
}
}
}
return null;
}
APÊNDICE H - XLPathProcessor.java
package xlpath.controller;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import xlpath.model.XLPathElementStore;
import xlpath.model.XLPathExpression;
import xlpath.model.XLPathStep;
}
if((elements.getArcs()!=null)&&(!elements.getArcs().isEmpty())){
List<Element> arcRefs = null;
for(Element arc : elements.getArcs()){
arcRefs = getArcReferences(arc,step.getLevel(),step.getAxis());
}
if((arcRefs!=null)&&(!arcRefs.isEmpty())){
for(Element arcRef : arcRefs){
axisElements.storeElement(arcRef);
}
}
}
if((elements.getResources()!=null)&&(!elements.getResources().isEmpty())){
List<Element> resourceRefs = null;
for(Element resource : elements.getResources()){
resourceRefs =
getResourceReferences(resource,step.getLevel(),step.getAxis());
}
if((resourceRefs!=null)&&(!resourceRefs.isEmpty())){
for(Element resourceRef : resourceRefs){
axisElements.storeElement(resourceRef);
}
}
}
return axisElements;
}
77
if(step.getAttributeSpec().equals("attribute")
&&
element.getAttribute("xlink:"+step.getAttributeName()).equals(step.getAttributeValue())){
auxElements.storeElement(element);
}else if(step.getAttributeSpec().equals("")){
auxElements.storeElement(element);
}
}
elementSpecElements = auxElements;
78
return elementSpecElements;
}
(docNodes.item(i).getAttributes().getNamedItem("xlink:type").getNodeValue().equals("locat
or"))) {
Element elementLocator = (Element)
docNodes.item(i);
String locatorHref =
elementLocator.getAttribute("xlink:href");
if(locatorHref!=null){
String locatorRef =
locatorHref.substring(locatorHref
.lastIndexOf("#") + 1,
locatorHref.length());
if
(remote.getAttribute("id").equals(locatorRef)) {
locators.add(elementLocator);
}
}
}
}
}
if(level.equals("LL")&&(axis.equals("linked"))){
return locators;
}else if(level.equals("LL")&&((axis.equals("arc-source"))||(axis.equals("arc-
destination")))){
return null;
}else if(level.equals("HL")&&(locators!=null)){
List<Element> arcs = new ArrayList<Element>();
for(Element locator : locators){
if(axis.equals("linked")||axis.equals("arc-source")){
Node link = locator.getParentNode();
for (int i = 0; i < link.getChildNodes().getLength(); i++)
{
if(link.getChildNodes().item(i).getNodeType()==1){
Element linkChild = (Element)
link.getChildNodes().item(i);
if((linkChild.hasAttribute("xlink:type"))
79
&&(linkChild.getAttribute("xlink:type").equals("arc"))){
if((linkChild.hasAttribute("xlink:from"))
&&(linkChild.getAttribute("xlink:from").equals(locator.getAttribute("xlink:label")))){
arcs.add(linkChild);
}
}
}
}
}if(axis.equals("linked")||axis.equals("arc-source")){
Node link = locator.getParentNode();
for (int i = 0; i < link.getChildNodes().getLength(); i++)
{
if(link.getChildNodes().item(i).getNodeType()==1){
Element linkChild = (Element)
link.getChildNodes().item(i);
if((linkChild.hasAttribute("xlink:type"))
&&(linkChild.getAttribute("xlink:type").equals("arc"))){
if((linkChild.hasAttribute("xlink:to"))
&&(linkChild.getAttribute("xlink:to").equals(locator.getAttribute("xlink:label")))){
arcs.add(linkChild);
}
}
}
}
}
}
return arcs;
}else{
return null;
}
}
if((element.hasAttribute("id"))&&(element.getAttribute("id").equals(remoteId))){
references.add(element);
i = nodes.getLength();
}
}
}
}
}
if(axis.equals("arc-source")||axis.equals("linked")){
for (int i = 0; i<link.getChildNodes().getLength(); i++) {
if(link.getChildNodes().item(i).getNodeType()==1){
Element linkChild = (Element) link.getChildNodes().item(i);
if((linkChild.getAttribute("xlink:type").equals("arc"))){
if((linkChild.hasAttribute("xlink:from"))
&&(linkChild.getAttribute("xlink:from").equals(locator.getAttribute("xlink:label")))){
references.add(linkChild);
}
}
}
}
}
if(axis.equals("arc-destination")||axis.equals("linked")){
for (int i = 0; i<link.getChildNodes().getLength(); i++) {
if(link.getChildNodes().item(i).getNodeType()==1){
Element linkChild = (Element) link.getChildNodes().item(i);
if((linkChild.hasAttribute("xlink:type"))
&&(linkChild.getAttribute("xlink:type").equals("arc"))){
if((linkChild.hasAttribute("xlink:to"))
&&(linkChild.getAttribute("xlink:to").equals(locator.getAttribute("xlink:label")))){
references.add(linkChild);
}
}
}
}
}
return references;
}
&&linkChild.getAttribute("xlink:label").equals(arc.getAttribute("xlink:from"))){
references.add(linkChild);
if(linkChild.getAttribute("xlink:type").equals("locator")){
locDest.add(linkChild);
}
}
}
if(axis.equals("arc-
destination")||axis.equals("linked")){
if(linkChild.hasAttribute("xlink:label")
&&linkChild.getAttribute("xlink:label").equals(arc.getAttribute("xlink:to"))){
references.add(linkChild);
if(linkChild.getAttribute("xlink:type").equals("locator")){
locSource.add(linkChild);
}
}
}
}
if(level.equals("HL")){
references.clear();
Document docXml = link.getOwnerDocument();
if(axis.equals("arc-source")||axis.equals("linked")){
if(locDest!=null){
for(Element locator : locDest){
String remoteUri =
locator.getAttribute("xlink:href");
if(remoteUri!=null){
String remoteId =
remoteUri.substring(remoteUri.lastIndexOf("#") + 1, remoteUri.length());
NodeList nodes =
docXml.getElementsByTagName("*");
Element element;
for(int j=0;
j<nodes.getLength(); j++){
if(nodes.item(j).getNodeType()==1){
82
if((element.hasAttribute("id"))&&(element.getAttribute("id").equals(remoteId))){
references.add(element);
}
}
}
}
}
}
}
if(axis.equals("arc-
destination")||axis.equals("linked")){
if(locSource!=null){
for(Element locator : locSource){
String remoteUri =
locator.getAttribute("xlink:href");
if(remoteUri!=null){
String remoteId =
remoteUri.substring(remoteUri.lastIndexOf("#") + 1, remoteUri.length());
NodeList nodes =
docXml.getElementsByTagName("*");
Element element;
for(int j=0;
j<nodes.getLength(); j++){
if(nodes.item(j).getNodeType()==1){
if((element.hasAttribute("id"))&&(element.getAttribute("id").equals(remoteId))){
references.add(element);
}
}
}
}
}
}
}
}
}
}
return references;
}
&&(linkChild.getAttribute("xlink:type").equals("arc"))){
if((linkChild.hasAttribute("xlink:from"))
&&(linkChild.getAttribute("xlink:from").equals(resource.getAttribute("xlink:label")))){
references.add(linkChild);
}
}
}
}
}
if(axis.equals("arc-destination")||axis.equals("linked")){
for (int i = 0; i<link.getChildNodes().getLength(); i++) {
if(link.getChildNodes().item(i).getNodeType()==1){
Element linkChild = (Element) link.getChildNodes().item(i);
if((linkChild.hasAttribute("xlink:type"))
&&(linkChild.getAttribute("xlink:type").equals("arc"))){
if((linkChild.hasAttribute("xlink:to"))
&&(linkChild.getAttribute("xlink:to").equals(resource.getAttribute("xlink:label")))){
references.add(linkChild);
}
}
}
}
}
return references;
}
}