嗨我想尝试从网址
读取XML数据XML结构如下:
<specialoffers>
<categories>...</categories>
<categories>...</categories>
<categories>...</categories>
<categories>...</categories>
<categories>...</categories>
<categories>...</categories>
XML:
<specialoffers>
<categories>
<category>
<![CDATA[ 0% Installment Payment Plan Offers ]]>
</category>
<merchants>
<merchantname>
<![CDATA[ EmaxIPP ]]>
</merchantname>
<merchantbigimage>
<![CDATA[
http://www.XXX.com/Images/Emax%20New%20-%20190x73-1_tcm20-48180.jpg]]>
</merchantbigimage>
<merchantsmallimage>
<![CDATA[
http://www.XXX.com/Images/Emax%20New%20-%20104x75-1_tcm20-48179.jpg
]]>
</merchantsmallimage>
<merchantmobileimage>
<![CDATA[ http://www.XXX.com ]]>
</merchantmobileimage>
<mobilehighlight>
<![CDATA[
Enjoy 0% Installment Payment Plan for 3 months on
all purchases made </b>
]]>
</mobilehighlight>
<locations>
<location>
<emirate>
<![CDATA[ XXX]]>
</emirate>
<address>
<![CDATA[ Center 1 ]]>
</address>
<latitude>
<![CDATA[ 51.169601 ]]>
</latitude>
<longitude>
<![CDATA[ 61.240395 ]]>
</longitude>
</location>
</merchants>
</categories>
</specialoffers>
Java代码如下:
URL url = new URL(URL);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(url.openStream());
NodeList nodeList = doc.getElementsByTagName("category");
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element)nodeList.item(i);
System.out.println(element.getFirstChild().getTextContent());
NodeList nodeList2 = doc.getElementsByTagName("merchants");
Element getChds = (Element)nodeList2.item(i);
for (int j=0; j < nodeList.getLength() ; j++){
NodeList nodeList3 = doc.getElementsByTagName("merchantname");
Element element1 = (Element)nodeList3.item(j);
System.out.println("--"+element1.getFirstChild().getTextContent());
}
}
我试图在所有“类别”中显示类别和商家名称,并且我能够显示所有类别的类别名称,但没有商家名称。
这是实际的xml字符串:http://www.adcb.com/specialoffers-test.xml
打印:
0% Installment Payment Plan Offers
--EmaxIPP
--Delma Medical Centre
.
.
Dining Offers
--Lounge Cafe
--India Palace Restaurant
.
.
答案 0 :(得分:2)
尝试打印merchants
时,实际上是在category
NodeList
nodeList
的长度上进行迭代。您需要迭代nodeList2
。
for (int j=0; j < nodeList2.getLength() ; j++){
NodeList nodeList3 = doc.getElementsByTagName("merchantname");
Element element1 = (Element)nodeList3.item(j);
System.out.println("--"+element1.getFirstChild().getTextContent());
}
您使用的nodeList
长度为6,而不是nodeList2
的长度为16.使用以上将打印
--EmaxIPP
--Delma Medical Centre
--Lounge Cafe
--India Palace Restaurant
--Ashas-Wafi
--Dome Cafe
--Delma Medical Center
--Jacky's Electronics
--Dreamland Aqua Park
--Yas Island Rotana
--Dubai Dolpharium
--Autodrome
--Singapore - Grand Hyatt Singapore
--Thailand - Dusit Thani Laguna Phuket
--Joyalukkas
--LifeStyle Fine Jewelry