[英]how to exclude tag from XML String in java
我正在編寫一段代碼來從網頁發送和接收數據。 我在Java中做這件事。 但是,當我“接收” xml數據時,它仍然在這樣的標記之間
<?xml version='1.0'?>
<document>
<title> TEST </title>
</document>
如何在Java中沒有標簽的情況下獲取數據。
這是我嘗試過的,該函數寫入數據,然后應獲取響應並在System.out.println
使用它。
public static String User_Select(String username, String password) {
String mysql_type = "1"; // 1 = Select
try {
String urlParameters = "mysql_type=" + mysql_type + "&username=" + username + "&password=" + password;
URL url = new URL("http://localhost:8080/HTTP_Connection/index.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
//System.out.println("Het werkt!!");
}
writer.close();
reader.close();
return line;
} catch (IOException iox) {
iox.printStackTrace();
return null;
}
}
提前致謝
在Java中使用DOMParser。 在Java文檔中進一步檢查
使用XML解析器解析XML。 這是Oracle教程的鏈接
只需從URLConnection
傳遞InputStream
Document doc = DocumentBuilderFactory.
newInstance().
newDocumentBuilder().
parse(conn.getInputStream());
從那里,您可以使用xPath查詢文檔的內容,或者只是遍歷文檔模型。
查看XML處理的Java API(JAXP) ,了解更多詳細信息
我建議僅使用RegEx來讀取XML,並獲取所需的標簽內容。 這簡化了您需要執行的操作,並限制了其他(不必要的)庫的包含。 然后,在這個主題上有很多StackOverflows: 用於XML解析的Regex , 在RegEx中,我想找到兩個XML標記之間的所有內容,僅提及其中兩個。
您必須使用XML解析器,在您的情況下,理想的選擇是JSoup ,它將從Web上刪除數據並解析XML和HTML格式,它將加載數據並進行解析並提供您想要的內容,下面是一個示例有用 :
1. URL中的XML
String xml = Jsoup.connect("http://localhost:8080/HTTP_Connection/index.php")
.get().toString();
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
String myTitle=doc.select("title").first();// myTitle contain now TEST
編輯:與您的請求一起發送GET或POST參數,請使用以下代碼:
String xml = Jsoup.connect("http://localhost:8080/HTTP_Connection/index.php")
.data("param1Name";"param1Value")
.data("param2Name","param2Value").get().toString();
您可以使用get()
調用HTTP GET
方法或post()
調用HTTP POST
方法。
2. XML從字符串
您可以使用JSoup解析String中的XML數據:
String xmlData="<?xml version='1.0'?><document> <title> TEST </title> </document>" ;
Document doc = Jsoup.parse(xmlData, "", Parser.xmlParser());
String myTitle=doc.select("title").first();// myTitle contain now TEST
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.