2010-12-14 17 views
14

Uso il seguente codice per analizzare il file XML.Analisi stringa XML in Android?

DocumentBuilderFactory factory; 
DocumentBuilder builder; 
InputStream is; 
Document dom; 
try { 
    factory = DocumentBuilderFactory.newInstance(); 
    is = new FileInputStream(strFileName); 
    builder = factory.newDocumentBuilder(); 

    dom = builder.parse(is); 
} 
catch(Exception e){} 

Invece del file XML esiste un modo per analizzare la stringa.

String xml="<?xml version="1.0"?> <name> Application</name> <demo> Demo </demo> </xml>"; 
+1

Che cosa si sta cercando di fare è molto chiaro. Se hai già una stringa - perché avresti bisogno di un parser XML? – Ofir

risposta

27

È possibile convertire la stringa a un InputStream utilizza ByteArrayInputStream:

String xml ="valid xml here"; 
InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8")); 

dom = builder.parse(is); 
+0

Grazie per il vostro aiuto – RMK

2

È possibile utilizzare StringReader:

StringReader sr = new StringReader(xml); 
InputSource is = new InputSource(sr); 
Document d = builder.parse(is); 
+0

Grazie per il vostro gentile aiuto !!! – RMK

+0

Se la seconda riga è 'InputSource è = new InputSource (sr);' invece? –

+0

Infatti, dovrebbe essere. Questo è corretto, grazie! –