简体   繁体   中英

Having trouble reading data from xml file

The object of my code is to create a shoppinglist from recipes stored in an xml file.

Im having trouble with how to get the data from the xml file and convert it into a list.

To start of I would love some help to just be able to print a simple list of the ingredients in the first recipe.

Heres my XML file:

<?xml version="1.0" encoding="UTF-8"?>
    <Drinks>
        <Drink id="Whiskey Sour">
            <ingredients group="Alkohol">
                <ingredient name="Whiskey" quantity="5" unit="cl">Whiskey</ingredient>
            </ingredients>
            <ingredients group="Mixer">
                <ingredient name="Friskpresset Citron" quantity="4" unit="cl">Friskpresset Citron</ingredient>
                <ingredient name="Sukkersirup" quantity="3" unit="cl">Sukkersirup</ingredient>
                <ingredient name="Æggehvide" quantity="½" unit="cl">Æggehvide</ingredient>
                <ingredient name="Angustura" quantity="2" unit="dash">Angustura</ingredient>
            </ingredients>
        </Drink>
        <Drink id="White Russian Frangelico">
            <ingredients group="Alkohol">
                <ingredient name="Vodka" quantity="3" unit="cl">Vodka</ingredient>
                <ingredient name="Kahlua" quantity="2" unit="cl">Kahlua</ingredient>
                <ingredient name="Frangelico" quantity="1" unit="cl">Frangelico</ingredient>
            </ingredients>
            <ingredients group="Mixer">
                <ingredient name="Sødmælk" quantity="3" unit="cl">Sødmælk</ingredient>
            </ingredients>
        </Drink>
        <Drink id="Espresso Martini">
            <ingredients group="Alkohol">
                <ingredient name="Vodka" quantity="3" unit="cl">Vodka</ingredient>
                <ingredient name="Kahlua" quantity="2" unit="cl">Kahlua</ingredient>
            </ingredients>
            <ingredients group="Mixer">
                <ingredient name="Kaffe" quantity="2" unit="cl">Kaffe</ingredient>
                <ingredient name="Sukkersirup" quantity="1" unit="cl">Sukkersirup</ingredient>
            </ingredients>
        </Drink>
    </Drinks>

And here is my code:

import java.io.File;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class CreateListOfGoods{

    public static void main (String argv[]) {
        try {
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File("src/Kartotek.xml")); 
            // normalize text representation
            doc.getDocumentElement ().normalize ();
            System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());    

            //Prints the amount of drinks in the database
            NodeList listOfDrinksNode = doc.getElementsByTagName("Drink");
            int totalDrinks = listOfDrinksNode.getLength();
            System.out.println("Total no of Drinks : " + totalDrinks);

            for(int s=0; s<listOfDrinksNode.getLength(); s++) {     
                Node listOfIngredientsNode = listOfDrinksNode.item(s);
                if(listOfIngredientsNode.getNodeType() == Node.ELEMENT_NODE) {
                    System.out.println("Virker if?");
                    //--------
                    NodeList alkoholList =  doc.getElementsByTagName("Ingredient");
                    Element alkoholElement = (Element)alkoholList.item(0);
                    String PrintAlkohol = alkoholElement.getTagName();

                    System.out.println(PrintAlkohol);
                }
            }
        } catch (SAXParseException err) {
            System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
            System.out.println(" " + err.getMessage ());
        } catch (SAXException e) {
            Exception x = e.getException ();
            ((x == null) ? e : x).printStackTrace ();
        } catch (Throwable t) {
            t.printStackTrace ();
        }
    }
}

Some of the variables are in Danish, but the code should be understandable. Hope some of you can guide me in the rigth direction

I've slightly modified the code. Now, it gathers all ingredients into list which is printed in the end of the program. It does it in 3 steps: 1) find all drinks; 2) find all ingredients groups; 3) find all ingredients in those groups and add them to list.

import org.w3c.dom.*;
import java.util.List;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


public class CreateListOfGoods{

public static void main (String argv[]) {
    try {
        List<String> listOfIngredients = new ArrayList<String>();
        String INGREDIENTS_TAG_NAME = "ingredients";
        String INGREDIENT_TAG_NAME = "ingredient";
        String DRINK_TAG_NAME = "Drink";
        String GROUP_ATTRIBUTE_NAME = "group";
        String INGREDIENT_NAME_ATTRIBUTE_NAME = "name";

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse (new java.io.File("src/Kartotek.xml"));
        // normalize text representation
        doc.getDocumentElement ().normalize ();
        System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());


        //Prints the amount of drinks in the database
        NodeList listOfDrinksNode = doc.getElementsByTagName(DRINK_TAG_NAME);
        int totalDrinks = listOfDrinksNode.getLength();
        System.out.println("Total no of Drinks : " + totalDrinks);

        for(int s=0; s<listOfDrinksNode.getLength(); s++) {

            // Find all ingredients groups
            NodeList groupNodes = listOfDrinksNode.item(s).getChildNodes();
            for(int i = 0; i < groupNodes.getLength(); i++) {
                if(groupNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
                    Element groupElement = (Element)groupNodes.item(i);
                    if(groupElement.getTagName().equals(INGREDIENTS_TAG_NAME)) {
                        System.out.println(String.format("group: %s", groupElement.getAttribute(GROUP_ATTRIBUTE_NAME)));

                        // Find all ingredients in group
                        NodeList ingredientNodes = groupElement.getChildNodes();
                        for(int j = 0; j < ingredientNodes.getLength(); j++) {
                            if(ingredientNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
                                Element ingredientElement = (Element)ingredientNodes.item(j);
                                if(ingredientElement.getTagName().equals(INGREDIENT_TAG_NAME)) {
                                    String ingredientName = ingredientElement.getAttribute(INGREDIENT_NAME_ATTRIBUTE_NAME);
                                    System.out.println(String.format("Ingredient name: %s", ingredientName));
                                    listOfIngredients.add(ingredientName);
                                }
                            }
                        }
                    }

                }
            }

        }

        System.out.println("All ingredients: " + listOfIngredients.toString());
    }catch (SAXParseException err) {
        System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
        System.out.println(" " + err.getMessage ());

    }catch (SAXException e) {
        Exception x = e.getException ();
        ((x == null) ? e : x).printStackTrace ();

    }catch (Throwable t) {
        t.printStackTrace ();
    }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM