Sto cercando di scrivere un codice che mi aiuti a creare un object XML. Per esempio, darò una stringa come input per una funzione e mi restituirà un XMLObject.
XMLObject convertToXML(String s) {}
Quando stavo cercando in rete, generalmente vedevo esempi sulla creazione di documenti XML. Quindi tutte le cose che ho visto sulla creazione di un XML e scrivere su un file e creare il file. Ma ho fatto qualcosa del genere:
Document document = new Document(); Element child = new Element("snmp"); child.addContent(new Element("snmpType").setText("snmpget")); child.addContent(new Element("IpAdress").setText("127.0.0.1")); child.addContent(new Element("OID").setText("1.3.6.1.2.1.1.3.0")); document.setContent(child);
Pensi che sia sufficiente creare un object XML? e inoltre puoi aiutarmi come ottenere dati da XML? Ad esempio, come posso ottenere IpAdress
da quel XML?
Grazie mille a tutti
EDIT 1: In realtà ora pensavo che forse sarebbe stato molto più facile per me avere un file come base.xml
, scriverò tutte le cose di base in questo ad esempio:
e quindi utilizzare questo file per creare un object XML. Cosa ne pensi di questo?
Se è ansible creare una stringa xml, è ansible trasformarla facilmente nell’object del documento xml, ad es.
String xmlString = " "; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(xmlString))); } catch (Exception e) { e.printStackTrace(); }
È ansible utilizzare l’object documento e le librerie di analisi xml o xpath per recuperare l’indirizzo IP.
provare qualcosa di simile
public static Document loadXML(String xml) throws Exception { DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance(); DocumentBuilder bldr = fctr.newDocumentBuilder(); InputSource insrc = new InputSource(new StringReader(xml)); return bldr.parse(insrc); }