Lesen von XML-Datei online
War ich auf der Suche code, den ich verwenden können, Lesen von XML-Datei. und ich fand eines, wie unten beschrieben. Aber mein problem ist, ich bin nicht in der Lage zu Lesen eine XML-Datei online. Wenn ich die URL der XML-Datei Lage, es gibt die Datei Nicht Gefunden Ausnahme. Kann jemand Rat. Vielen Dank im Voraus.
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLReader {
public static void main(String argv[]) {
try {
File file = new File("MyXML.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("employee");
System.out.println("Information of all employees");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
System.out.println("First Name : " + ((Node) fstNm.item(0)).getNodeValue());
NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = lstNmElmnt.getChildNodes();
System.out.println("Last Name : " + ((Node) lstNm.item(0)).getNodeValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
mögliche Duplikate von gewusst Wie: Lesen von XML-Antwort aus einer URL in java?
InformationsquelleAutor Jay Mayu | 2011-05-08
Du musst angemeldet sein, um einen Kommentar abzugeben.
War es discoused auf stackoverflow: Gewusst wie: Lesen von XML-Antwort aus einer URL in java?
Vielen Dank, es funktionierte wie Magie 🙂
InformationsquelleAutor Marcin
Nutzen Sie das java.net.URL-Klasse:
InformationsquelleAutor bdoughan
Wenn Sie versuchen, die Kommunikation mit einem Restful-Service, könnten Sie profitieren von der Nutzung einer Bibliothek. Open-source-Bibliotheken mit goodies in diesem Bereich sind Apache CXF und Jersey.
InformationsquelleAutor bmargulies