0
我能夠通過使用XML DOM解析器解析XML的主要元素,例如我可以獲取getElementsByTagName(「id」)或getElementsByTagName(「stock_number」)等等上,但我遇到了一個問題,因爲在標籤我需要能夠只返回的信息。java DOM XML解析器內部元素
我在文件中的XML feed.xml這樣的:
<inventory>
<item UnitID="1234" Record="0">
<id>1234</id>
<dealerid>455</dealerid>
<stock_number>1600Xtreme</stock_number>
<make>Nvidia</make>
<noteshtml>This is some random info about the product1234.<br><br>
Buy with trust from a LQZ dealership.<br><br> Contact Dave at
Burnaby location - 604 123 4578.<br>
</noteshtml>
<images>
<Image1 image="1" UnitID="1234">
https://anydomain.com/photo54.jpg
</Image1>
<Image2 image="2" UnitID="1234">
https://anydomain.com/photo22.jpg
</Image2>
<Image3 image="3" UnitID="1234">
https://anydomain.com/photo32.jpg
</Image3>
</images>
</item>
<item UnitID="7854" Record="1">
<id>7854</id>
<dealerid>587</dealerid>
<stock_number>12TMAX5500</stock_number>
<make>Realtek</make>
<noteshtml>This is some random info about the product 7854.<br><br>
Buy with trust from a LQZ dealership.<br><br> Contact Dave at
Burnaby location - 604 123 4578.<br>
</noteshtml>
<images>
<Image1 image="1" UnitID="7854">
https://anydomain.com/photo656.jpg
</Image1>
<Image2 image="2" UnitID="7854">
https://anydomain.com/photo6565.jpg
</Image2>
<Image3 image="3" UnitID="7854">
https://anydomain.com/photo908.jpg
</Image3>
</images>
</item>
</inventory>
這是一般我的Java代碼,我得到了什麼至今:
File fXmlFile=new File("feed.xml");
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder=dbFactory.newDocumentBuilder();
Document doc=dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList=doc.getElementsByTagName("item");
for (int temp=0; temp < nList.getLength(); temp++)
{
Node nNode=nList.item(temp);
Element eElement2=(Element)nNode;
int search=1234;
System.out.println("This is the value to search from my variable: " + search);
int toTest=Integer.parseInt(eElement2.getAttribute("UnitID"));
System.out.println("toTest is equal to: " + toTest);
if (toTest == search)
{
System.out.println("stock Number: " + eElement2.getElementsByTagName("stock_number").item(0).getTextContent());
}
}
我的問題是如何現在進入圖像標籤,並只打印該圖像= 1標識符的URL。
我有很多搜索,並研究如何使用DOM解析器,我嘗試通過創建節點的子元素,但我得到錯誤。 我很感謝你的回答。