Use algum pacote como o JDOM, DOM4J ou o próprio suporte a XML do Java, e pegue os valores dos atributos.
T
tm474
Eu tentei fazer isso mas fica dando um erro:
O codigo que eu usei foi esse:
InputSourcesource=newInputSource(newStringReader(stringXML));try{Documentdoc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(source);NodeListnl=doc.getElementsByTagName("Detail");Nodenode=nl.item(0);System.out.println(node.getFirstChild().getNodeValue());}catch(SAXExceptione){// TODO Auto-generated catch blocke.printStackTrace();}catch(IOExceptione){// TODO Auto-generated catch blocke.printStackTrace();}catch(ParserConfigurationExceptione){// TODO Auto-generated catch blocke.printStackTrace();}catch(FactoryConfigurationErrore){// TODO Auto-generated catch blocke.printStackTrace();}}
e aparece esse erro:
“org.xml.sax.SAXParseException: Expecting quoted value for attribute value version.”
T
thingol
importjava.io.StringReader;importjava.util.LinkedHashMap;importjava.util.Map;importjavax.xml.xpath.XPath;importjavax.xml.xpath.XPathConstants;importjavax.xml.xpath.XPathExpression;importjavax.xml.xpath.XPathFactory;importorg.w3c.dom.Node;importorg.w3c.dom.NodeList;importorg.xml.sax.InputSource;publicclassExemploParsingXML{publicstaticvoidmain(String[]args)throwsException{XPathxpath=XPathFactory.newInstance().newXPath();XPathExpressionxpe=xpath.compile("/Details/Detail");// isto é lento, faça uma vezStringstrXML="<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 pegarNodeListnodeList=(NodeList)xpe.evaluate(newInputSource(newStringReader(strXML)),XPathConstants.NODESET);Map<String,String>atributos=newLinkedHashMap<String,String>();for(inti=0,n=nodeList.getLength();i<n;++i){Nodenode=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.