Obter informações de arquivo XML

Oi Pessoal,

Estou precisando ler os valores da tag dentro da tag do seguinte arquivo XML:

<?xml version="1.0" encoding="utf-8"?>
<lom xmlns="http://www.imsglobal.org/xsd/imsmd_rootv1p2p1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd">
	<general>
		<title>
			<langstring xml:lang="x-none">KS3Sci Behaviour</langstring>
		</title>
		<catalogentry>
			<catalog>JSH</catalog>
			<entry>
				<langstring xml:lang="x-none">JSH3SCQ41</langstring>
			</entry>
		</catalogentry>
		<language>en</language>
		<description>
			<langstring xml:lang="x-none">This is a science quiz containing ten interactive questions.</langstring>
		</description>
		<keyword>
			<langstring xml:lang="x-none">test,interactive,jsh,quiz</langstring>
		</keyword>
	</general>
	<lifecycle>
		<version>
			<langstring xml:lang="x-none">1.0</langstring>
		</version>
		<status>
			<source>
				<langstring xml:lang="x-none">LOMv1.0</langstring>
			</source>
			<value>
				<langstring xml:lang="x-none">Final</langstring>
			</value>
		</status>
	</lifecycle>
	<metametadata>
		<metadatascheme>ADL SCORM 1.2</metadatascheme>
	</metametadata>
	<technical>
		<format>text/html</format>
		<location>Blank.htm</location>
	</technical>
	<educational>
		<learningresourcetype>
			<source>
				<langstring xml:lang="x-none">LOMv1.0</langstring>
			</source>
			<value>
				<langstring xml:lang="x-none">Exercise</langstring>
			</value>
		</learningresourcetype>
	</educational>
	<rights>
		<cost>
			<source>
				<langstring xml:lang="x-none">LOMv1.0</langstring>
			</source>
			<value>
				<langstring xml:lang="x-none">yes</langstring>
			</value>
		</cost>
		<copyrightandotherrestrictions>
			<source>
				<langstring xml:lang="x-none">LOMv1.0</langstring>
			</source>
			<value>
				<langstring xml:lang="x-none">yes</langstring>
			</value>
		</copyrightandotherrestrictions>
		<description>
			<langstring xml:lang="x-none">Subject to copyright restrictions.</langstring>
		</description>
	</rights>
	<classification>
		<purpose>
			<source>
				<langstring xml:lang="x-none">LOMv1.0</langstring>
			</source>
			<value>
				<langstring xml:lang="x-none">Educational Objective</langstring>
			</value>
		</purpose>
		<description>
			<langstring xml:lang="x-none">This science quiz covers the topic of human and animal behaviour.</langstring>
		</description>
		<keyword>
		<langstring xml:lang="x-none">science,test,questions,behaviour,learned,innate,instincts,imitating,mimic,psychology,ethology</langstring>
	</keyword>
	</classification>
</lom>

Ou seja, queria pegar os valores science,test,questions,behaviour,learned,innate,instincts,imitating,mimic,psychology,ethology.
Entretanto, com algumas restrições:
-Um mesmo arquivo pode ter várias tags ;
-Cada tag pode ter várias tags ;
-Preciso pegar esses valores de forma separada pelas vírgulas.

Comecei a pesquisar e vi um monte de formas de se fazer isso. Comecei a fazer e até consegui pegar os valores, porém com algumas restrições. Uma delas é que apenas consigo pegar os valores quando tenho os valores diretamente na tag , tipo assim: valor1, valor2, valor3. Outra restrição é que não consigo pegar os valores separados pela vírgula. Enfim, meu código ficou assim:

package testPackage;
import java.util.Vector;
import javax.xml.parsers.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class LOXmlReader {
	private String xmlPathName;

	public LOXmlReader(String xmlPathName){
		this.xmlPathName = xmlPathName;
	}
	
	public Vector readLOTag() throws Exception{
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(this.xmlPathName);
		
		Element element = doc.getDocumentElement();
		
		NodeList classificationNode = element.getElementsByTagName("classification");
		
		Vector classificationTagValues = new Vector();
		
		//Percorre cada elemento classification encontrado.
		for (int i=0; i<classificationNode.getLength();i++){
			Element classificationTag = (Element) classificationNode.item(i);

			//Pega as dados cadastrados na tag keyword da tag classification atual
			String keyword = getChildTagValue(classificationTag,"keyword");
			
			//Cria uma nova instância do LOContent encontrado
			LOContent loContent = new LOContent(keyword);
			classificationTagValues.addElement(loContent);
		}
		return classificationTagValues;
	}
	
	private String getChildTagValue(Element element, String tagName) throws Exception{
		NodeList children = element.getElementsByTagName(tagName);
		if (children==null){
			return null;
		}
		
		Element child = (Element) children.item(0);
		if (child==null){
			return null;
		}
		return child.getFirstChild().getNodeValue();
	}
}

Alguém poderia me ajudar, dar alguma dica? Essa é a melhor forma de se fazer? Peço desculpas por qualquer besteira q tenha falado, mas é q sou meio capenga em desenvolvimento java, porém estou precisando desse trecho de código para um projeto da pós.

Grato.

PROCURE SOBRE Xstrean ou DOM…

mais pra leitura acho melhor o DOM …

[quote=kiq095]PROCURE SOBRE Xstrean ou DOM…

mais pra leitura acho melhor o DOM …[/quote]

foi mal respondi antes de ler …!!!
hehehe

olha esse exemplo aqui:

tem comentario e deve te ajudar um pouco

[code]
String []Campo_fornecedor;
String campo="";
int cont=0;

try{

   //fazer o parse do arquivo e criar o documento XML

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = (Document) db.parse(file);

		//Passo 1: obter o elemento raiz
		Element raiz = doc.getDocumentElement();
		//Passo 2: localizar os elementos filhos da agenda

		NodeList listaContatos = raiz.getElementsByTagName("No_PAI");
		//Passo 3: obter os elementos de cada elemento contato
			//como cada elemento do NodeList é um nó, precisamos fazer o cast
			Element contato = (Element) listaContatos.item(0);
			//Passo 4: obter o atributo id do contato

			//Passo 5: obtém o nome do DRIVER__FORNECEDOR
			NodeList listaNomes = (NodeList)  contato.getElementsByTagName("NO_FILNHO");
                            cont=listaNomes.getLength();
                            
                           
			for(int k=0;k<cont;k++){// pervorret todo o arquivo procurando os dados

                                Node string =listaNomes.item(k).getFirstChild();

                                if(string !=null){

                                     campo=string.getNodeValue();
                                     Campo_fornecedor[k]=campo;

                                     test=true;
                                }
                              }       

}
catch(Exception ex){

        ex.printStackTrace();
        test=false;
        JOptionPane.showMessageDialog(null, "ERRO AO RECUPERAR OS CAMPOS "+ex.toString(),"ERRO  20",JOptionPane.ERROR_MESSAGE);

} [/code]

ou seja e so vc colocar o nome do pai e consegue recuperar os dados …!!!
e aqui recupera todos os dados … ate mesmo se tiver masi de um filho …

da uma olhadinha ai

1 curtida

Ok kiq95, vou olhar agora.

Vlw!

qualquer coisa da uma olhadinha aqui …!!!

http://www.loiane.com/category/tutorial/xml/

Me ajudou, estou pegando a tag (quantas tiver no arquivo) e a tag . Porém, continuo com o problema de que só consigo pegar os valores dessa tag se ela estiver assim:

<keyword> valor1,valor2, valor3 <keyword>

Porém, ela está assim:

<keyword>teste,teste2
	<langstring xml:lang="x-none">science,test,questions,behaviour,learned,innate,instincts,imitating,mimic,psychology,ethology</langstring>
</keyword>

Daí, tentei usar a mesma lógica que usei para pegar a tag dentro da tag para pegar a tag dentro da tag . Acretito que seja algo relacionado ao atributo dentro da tag. Porém, não sei como avançar. Algúme dá uma luz?
Vlw.

Consegui consegui. Era um erro de “visão” mesmo…minha visão :slight_smile:

Tinha esquecido de fechar o post.

Agradeço aos colegas. Vlw.