Duvida com XML para HashMap

4 respostas
T

Então,

eu preciso fazer um parsing em uma string XML e colocar o valores em um HashMap. A string seria:

String strXML =

;

E eu tenho que obter um HashMap, onde as chaves seriam as tags (“name”, “value”) e os campos seriam os valores das tags.

Se alguem puder por favor me ajudar.

Desde já obrigado.

4 Respostas

T

Use algum pacote como o JDOM, DOM4J ou o próprio suporte a XML do Java, e pegue os valores dos atributos.

T

Eu tentei fazer isso mas fica dando um erro:

O codigo que eu usei foi esse:

InputSource source = new InputSource(new StringReader(stringXML));

     try {
	    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(source);
	    NodeList nl = doc.getElementsByTagName("Detail");
	    Node node = nl.item(0);
	    System.out.println(node.getFirstChild().getNodeValue());
	    
	} catch (SAXException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (ParserConfigurationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (FactoryConfigurationError e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}	
}

e aparece esse erro:

“org.xml.sax.SAXParseException: Expecting quoted value for attribute value version.”

T
import java.io.StringReader;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class ExemploParsingXML {
	public static void main(String[] args) throws Exception {

		XPath xpath = XPathFactory.newInstance().newXPath();
		XPathExpression xpe = xpath.compile("/Details/Detail"); // isto é lento, faça uma vez

		String strXML = "<Details><Detail name='ConfigurationFileDescription' value='token.conf' /><Detail name='ConfigurationFileLocation' value='c:/configuracoes/temp.ini' /></Details>";
		
		// Queremos pegar todos os elementos "/Details/Detail" e obter
		// seus atributos
		// Isto pode ser feito para cada string que você for pegar
		NodeList nodeList = (NodeList) xpe.evaluate(new InputSource(
				new StringReader(strXML)), XPathConstants.NODESET);
		Map<String,String> atributos = new LinkedHashMap<String,String>();
		for (int i = 0, n = nodeList.getLength(); i < n; ++i) {
			Node node = nodeList.item(i);
			atributos.put (node.getAttributes().getNamedItem("name").getNodeValue(),
			               node.getAttributes().getNamedItem("value").getNodeValue());
		}
		System.out.println (atributos);
	}
}

Atenção - você TEM DE USAR XML Válido. Veja um exemplo de XML válido no meu programa.

T

Muito obrigado thingol.

Criado 12 de junho de 2008
Ultima resposta 12 de jun. de 2008
Respostas 4
Participantes 2