I'm learning how to write parsers in Java, now I'm trying to make a DOM XML Parser, but my parser doesn't display all the data from my XML file. What's the problem? Can somebody help me?
Here's the class for DOM Parser:
public class DOMParser2 {
private static Shoes getShoes(Node node) {
Shoes shoes = new Shoes();
if(node.getNodeType() == Node.ELEMENT_NODE){
Element element = (Element) node;
shoes.setTitle(getTagValue("ss:title", element));
shoes.setBrand(Brand.fromValue(getTagValue("ss:brand", element)));
shoes.setCategory(Category.fromValue(getTagValue("ss:category", element)));
shoes.setSeason(Season.fromValue(getTagValue("ss:season", element)));
shoes.setPrice(Double.parseDouble(getTagValue("ss:price", element)));
}
return shoes;
}
private static String getTagValue(String tag, Element element){
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodeList.item(0);
return node.getNodeValue();
}
public static void main(String[] args){
String filepath = "ShoesShop.xml";
File xmlFile = new File(filepath);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlFile);
document.getDocumentElement().normalize();
System.out.print("Root element: " + document.getDocumentElement().getNodeName());
NodeList nodeList = document.getElementsByTagName("ss:ShoesShop");
List<Shoes> shoesList = new ArrayList<Shoes>();
for(int i = 0; i<nodeList.getLength(); i++){
shoesList.add(getShoes(nodeList.item(i)));
}
for (Shoes shoes:shoesList){
System.out.println();
System.out.println(shoes.toString());
}
} catch(Exception exc){
exc.printStackTrace();
}
}
}
As a result I get this:
Root element: ss:ShoesShop [title=Baltrum, brand=GUCCI, category=BOOTS, season=FALL, price=734.0]
Here's an XML-file
<ss:ShoesShop xmlns:ss="http://www.example.org/ShoesShop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.org/ShoesShop ShoesShop.xsd ">
<ss:shoes id="1" stock="true">
<ss:title>Baltrum</ss:title>
<ss:brand>Gucci</ss:brand>
<ss:category>Boots</ss:category>
<ss:season>fall</ss:season>
<ss:price>734.0</ss:price>
</ss:shoes>
<ss:shoes id="2" stock="true" mostWanted = "true">
<ss:title>Amalfi</ss:title>
<ss:brand>Dior</ss:brand>
<ss:category>Mules</ss:category>
<ss:season>winter</ss:season>
<ss:price>364.0</ss:price>
</ss:shoes>
</ss:ShoesShop>