java


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 ();
}
}
}

Related Links

Remove the duplicate characters in a string
How to make a filter based on selected items
Regex to return the characters between square brackets (but not the brackets)
Variable Allocation and the change allocated Objects
How to access public static variable in a Java class from a JSP
Spring over Tomee configuration
What is the purpose of Escape Sequence \' in java?
Map a list of object to another list using Dozer's custom converters
Java- Graphics are not working for JPanel class once called by another class
Getting java.lang.nullPointerException for populating from existing database [duplicate]
Why doesnt it get data from SQLite database?
ClassNotFound: VMDisconnectedException) after losing .bashrc
Put and get a map from Libgdx preferences
Scanner input not working (Java)? [closed]
Java method that returns a function?
java refer to component by a variable name [closed]

Categories

HOME
netbeans
keycloak
reflection
c#-4.0
reserved
tinymce
hashmap
infragistics
serverspec
virtualization
wheelnav.js
modelica
spring-tool-suite
ups
quartz-scheduler
iolanguage
progressive-web-apps
footer
propel
interop
jqwidget
ml
intentfilter
ehcache
css-animations
mmap
rst2pdf
fopen
maxmind
strncpy
buck
delicious-api
google-cloud-endpoints-v2
catch-all
openoffice.org
geopositioning
mapdb
picasso
io-redirection
file-format
hilbert-curve
leading-zero
dism
sas-visual-analytics
core-plot
angular2-meteor
apple-news
long-polling
rainbowtable
jquery-validate
paxos
dotnetzip
integrity
slickedit
zendesk-app
quartz-composer
nxt
multi-level
pcf
xml-attribute
plottable.js
websitepanel
multiple-regression
ready-api
dlna
itextpdf
unity-networking
qtableview
execute
fouc
browser-bugs
twirl
proj4js
facebook-graph-api-v2.4
jsonpickle
heisenbug
wp-query
poller
meteor-velocity
app42
shellexecute
delphi-6
chuck
cascalog
hgsubversion
xmemcached
floating
yslow
digest-authentication
wise
sef
eqatec
thread-local-storage
mdac

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App