Come analizzare un XML con dati inclusi in <![CDATA[---]...
come è possibile analizzare l'xml e ottenere i dati inclusi in CDATA
???Come analizzare XML per <![CDATA[]]>
risposta
public static void main(String[] args) throws Exception {
File file = new File("data.xml");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//if you are using this code for blackberry xml parsing
builder.setCoalescing(true);
Document doc = builder.parse(file);
NodeList nodes = doc.getElementsByTagName("topic");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("title");
Element line = (Element) title.item(0);
System.out.println("Title: " + getCharacterDataFromElement(line));
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
(http://www.java2s.com/Code/Java/XML/GetcharacterdataCDATAfromxmldocument.htm)
Preferirei fare qualcosa come: if (child! = Null && (child instanceof CharacterData)) { return ((CharacterData) child) .getData(); } else { return e.getNodeValue(); } Per gestire perfettamente la presenza/assenza del blocco CDATA. –
Potete per favore fornire del testo per descrivere cosa state facendo e perché usereste il 'DocumentBuilderFactory'? – Gray
Nell'attuale implementazione del DOM Java è possibile accedere a CDATA semplicemente come dati di testo usando 'e.getTextContent()'. [Vedi esempio] (http://stackoverflow.com/questions/42802202) senza controllo del tipo, cast, 'e.getData()'. – jschnasse
CDATA
dice solo che i dati inclusi non devono essere sfuggiti. Quindi, prendi il testo del tag. Il parser XML dovrebbe restituire i dati chiari senza CDATA
.
ottenere i dati di testo: e.getTextContent(); –
qui r.get().getResponseBody()
è il corpo della risposta
Document doc = getDomElement(r.get().getResponseBody());
NodeList nodes = doc.getElementsByTagName("Title");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("Child tag where cdata present");
Element line = (Element) title.item(0);
System.out.println("Title: "+ getCharacterDataFromElement(line));
public static Document getDomElement(String xml) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setCoalescing(true);
dbf.setNamespaceAware(true);
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
Dal momento che tutte le risposte precedenti si utilizza un approccio basato DOM. Ecco come analizzare CDATA con un approccio basato sul flusso utilizzando STAX.
Utilizzare il seguente schema:
switch (EventType) {
case XMLStreamConstants.CHARACTERS:
case XMLStreamConstants.CDATA:
System.out.println(r.getText());
break;
default:
break;
}
campione completo:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
public void readCDATAFromXMLUsingStax() {
String yourSampleFile = "/path/toYour/sample/file.xml";
XMLStreamReader r = null;
try (InputStream in =
new BufferedInputStream(new FileInputStream(yourSampleFile));) {
XMLInputFactory factory = XMLInputFactory.newInstance();
r = factory.createXMLStreamReader(in);
while (r.hasNext()) {
switch (r.getEventType()) {
case XMLStreamConstants.CHARACTERS:
case XMLStreamConstants.CDATA:
System.out.println(r.getText());
break;
default:
break;
}
r.next();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (r != null) {
try {
r.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
Con /path/toYour/sample/file.xml
<data>
<![CDATA[ Sat Nov 19 18:50:15 2016 (1672822)]]>
<![CDATA[Sat, 19 Nov 2016 18:50:14 -0800 (PST)]]>
</data>
Dà:
Sat Nov 19 18:50:15 2016 (1672822)
Sat, 19 Nov 2016 18:50:14 -0800 (PST)
- 1. Come analizzare XML SOAP?
- 2. come analizzare xml in hashmap?
- 3. Come posso analizzare XML Android?
- 4. Come analizzare XML in PHP?
- 5. Usa Css esterno per analizzare XML
- 6. Utilizzando XPath per analizzare un documento XML
- 7. analizzare XML in PowerShell
- 8. Modo per analizzare XML (org.w3c.Document) su Android
- 9. Script Perl per analizzare XML usando XML :: LibXML;
- 10. Il modo più efficiente per analizzare Xml
- 11. C: Come analizzare XML in Android?
- 12. Come analizzare il file XML in RapidXML
- 13. Come analizzare XML nel backend Meteor?
- 14. Come analizzare XML all'oggetto java utilizzando XStream
- 15. Come analizzare la risposta XML utilizzando jQuery
- 16. Perl, come analizzare il file XML, xpath
- 17. Come analizzare una stringa XML in Qt
- 18. come analizzare un xml da ANT
- 19. Come analizzare XML usando il parser SAX
- 20. Come si usa Nokogiri per analizzare un file XML?
- 21. come passare un file xml a lxml per analizzare?
- 22. XML per IEnumerable <T>
- 23. Android: miglior parser per analizzare i dati XML
- 24. Python - Qual è più veloce per analizzare Json o XML?
- 25. Perl XML semplice per analizzare nodo con lo stesso nome
- 26. Metodo migliore per analizzare vari documenti XML personalizzati in Java
- 27. FileNotFoundException durante la lettura del file .xml per analizzare
- 28. Come posso generare XML con Nokogiri senza "<? Xml version = ..."?
- 29. Come ottenere XML con intestazione (<? Xml version = "1.0" ...)?
- 30. Come analizzare xml in Python su Google App Engine
Analizza il file "a mano" o utilizza una classe XMLReader (e quali)? – Thargor