[英]Parse complex element XML in Java with DOM
<message>
<element1>
<arrival point="string">
<positionAndTime>
<Time>
<estimated time="2017-10-14T10:43:00Z"/>
</Time>
</positionAndTime>
</arrival>
</element1>
<element2>
<depart point="string">
<positionAndTime>
<Time>
<estimated time="2017-10-14T10:43:00Z"/>
</Time>
</positionAndTime>
</depart>
</element2>
</message>
這是我的XML文檔的簡化版本。 我正在編寫一個JavaEE應用程序,但對解析XML感到困惑。 到目前為止,我已經能夠遍歷它並從到達點=字符串和出發點=字符串接收字符串,但是我在理解如何從元素1和2獲取“估計時間”塊方面遇到問題。我可以簡單地getElementsByTagName但由於它們在elements1和2中被命名為相同,因此我需要將它們分開。
很簡單!
為了區分,您將它們帶入Pojo課堂,在其中您以不同的方式命名。
class MessageParser{
private String arrivalEstimatedTime;
private String departureEstimatedTime;
..
//getters and setters
public String getArrivalEstimatedTime() {
return arrivalEstimatedTime;
}
public void setArrivalEstimatedTime(String arrivalEstimatedTime) {
this.arrivalEstimatedTime = arrivalEstimatedTime;
}
public String getDepartureEstimatedTime() {
return departureEstimatedTime;
}
public void setDepartureEstimatedTime(String departureEstimatedTime) {
this.departureEstimatedTime = departureEstimatedTime;
}
}
遍歷xml時,您知道自己的位置(到達標簽或離開標簽)
因此,當您在<arrival point="string">
標記內時,將值設置如下
MessagePojo message=new MessagePojo();
message.SetArrivalEstimatedTime(arrival_Time_From_XML);
預計出發時間也是如此。
現在您有了data(arrivalEstimatedTime,departureEstimatedTime),可以根據需要發送值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.