Ler arquivo xml com java

0 respostas
T

Bom dia, eu estava procurando no forum uma maneira de ler um arquivo xml, e não consegui ler um arquivo da maneira que eu preciso.

Preciso ler um arquivo xml, que vai estar assim:

<jas>
	<package name="com.br.vra.administrar">
		<service name="VRA_Proprietario_AssociarRecurso">
			<action name="Listar">
				<result>VRA_Proprietario_AssociarRecurso_Lista</result>			
			</action>
			<action name="Incluir">
				<result>VRA_Proprietario_AssociarRecurso_Manutencao</result>
			</action>
			<action name="Alterar">
				<result>VRA_Proprietario_AssociarRecurso_Manutencao</result>
			</action>
			<action name="Excluir">
				<result>VRA_Proprietario_AssociarRecurso_Manutencao</result>
			</action>
		</service>
	</package>
</jas>

Preciso pegar todas as tags e os atributos do xml, como por exemplo:
String pacote = com.br.vra.administrar
String service = VRA_Proprietario_AssociarRecurso
String action = Listar
String result = VRA_Proprietario_AssociarRecurso_Lista
String action = Incluir
String result = VRA_Proprietario_AssociarRecurso_Manutencao
Assim por diante…

Segue meu código java:

package com.vra.core;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Util {

	public static String[] xmlReader(String filePath, String[] nodes,
			String attributeName) throws Exception {

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(filePath);
		Element elem = doc.getDocumentElement();

		NodeList nl = elem.getElementsByTagName(nodes[0]);
		Element tag = (Element) nl.item(0);
		int size = nodes.length - 1;
		String[] no = new String[size];
		for (int i = 0; i < size; i++) {
			no[i] = getChildTagValue(tag, nodes[i + 1]).trim()
					+ getChildAttributeValue(tag, nodes[i + 1], attributeName)
							.trim();
		}
		return no;
	}

	private static String getChildTagValue(Element elem, String tagName)
			throws Exception {
		NodeList children = elem.getElementsByTagName(tagName);
		Element child = (Element) children.item(0);
		if (children == null || child == null)
			return null;
		Node no = child.getFirstChild();
		return no.getNodeValue();
	}

	public static String getChildAttributeValue(Element elem, String tagName,
			String attributeName) throws Exception {
		NodeList children = elem.getElementsByTagName(tagName);
		Element child = (Element) children.item(0);
		child.getAttribute(attributeName);
		if (children == null || child == null)
			return null;
		return child.getAttribute(attributeName);
	}
}
Criado 28 de fevereiro de 2008
Respostas 0
Participantes 1