<hotel hotelCode="FR000715" hotelRating="3STR">
<hotelName>Kyriad Paris Porte D'Ivry</hotelName>
<hotelChain code="">Simply Hotels</hotelChain>
<city code="FRIVS" standard="LOCODE">Ivry-Sur-Seine</city>
<geoLocalization latitude="48.819761" longitude="2.376128"/>
<address>1-11, Rue René Villars 94200 Ivry-Sur-Seine</address>
<phone>00 33 1 46 71 00 17</phone>
<fax>00 33 1 46 58 91 00</fax>
<email>email@test.com</email>
</hotel>
我想从上面的代码中获取hotelCode
,hotelRating
,hotelName
,city
,geoLocalization
这是我的代码:
DOMParser parser = DOMParser.getInstance();
parser.parse(responseStr);
Document document = parser.getDocument();
NodeList response = document.getElementsByTagName("hotel");
for (int hd = 0; hd < response.getLength(); hd++) {
for (int j = 0; j < response.item(hd).getChildNodes().getLength(); j++) {
Node referenceChild = response.item(hd).getChildNodes().item(j);
if (null != referenceChild.getLocalName()) {
if (referenceChild.getLocalName().equals("hotelName")) {
hotelName = referenceChild.getFirstChild().getNodeValue();
}
}
}
}
只有我才能收到hotelName
。但不是其他标签。我想分别获取所有子节点值。
答案 0 :(得分:1)
您可以使用&#34; element.getAttribute&#34;
for (int hd = 0; hd < response.getLength(); hd++) {
Node nNode = response.item(hd);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
hotelCode=eElement.getAttribute("hotelCode");
hotelRating=eElement.getAttribute("hotelRating");
for (int j = 0; j < response.item(hd).getChildNodes().getLength(); j++) {
Node referenceChild = response.item(hd).getChildNodes().item(j);
if (null != referenceChild.getLocalName()) {
if (referenceChild.getLocalName().equals("hotelName")) {
hotelName = referenceChild.getFirstChild().getNodeValue();
}
else if (referenceChild.getLocalName().equals("city")) {
city = referenceChild.getFirstChild().getNodeValue();
}
else if (referenceChild.getLocalName().equals("geoLocalization")) {
if (referenceChild.getNodeType() == Node.ELEMENT_NODE) {
Element eChildElement = (Element) referenceChild;
latitude=eChildElement.getAttribute("latitude");
longitude=eChildElement.getAttribute("longitude");
}
}
}
}
}
}
更多详情请查看此链接 https://www.tutorialspoint.com/java_xml/java_dom_parse_document.htm