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

Best practices for dealing with exceptions in a synchronized block/method in Java [closed]
Container of Enums in java
Map Type , HashMap constructor [duplicate]
Applying blur using RenderScript in Android creates weird output
Convert regular date and time to Julian date and vice versa
Java NoClassDefFoundError, Not Sure What's Wrong
Not sure I am using inheritance/polymorphism issue?
Finding the Mode of Integers in an Array
How to configure embedded Tomcat integrated with Spring to listen requests to IP address, besides localhost?
Access Canvas From JFrame
For PBKDF2, using HMAC-SHA256 is more secure than using HMAC-SHA-1?
Get Value from XML string
How to get radio button's id and convert to string?
Hamcrest Matchers - Assert Type of List
how to sort List<Object[]>?
How to use GridBagLayout to make a JLabel 1 column wide and then a JTextField 2 columns wide (for a total width 3 columns)

Categories

HOME
magnific-popup
google-api-php-client
nullpointerexception
relative-path
mean-stack
rsyslog
tizen-web-app
malloc
jsrender
win32gui
fingerprint
echarts
slurm
session-variables
node-pdfkit
google-cloud-spanner
commonmark
lombok
highlight.js
amazonsellercentral
one-hot-encoding
cloudhub
web-sql
css-animations
kannel
phpfox
buck
ejabberd-module
msys2
jspm
atlassian-crucible
gsmcomm
bpel
fabric8
react-chartjs
junit5
functor
pim
atl
simplexml
espeak
android-browser
vapor
temporary-files
preconditions
gzipstream
gulp-sourcemaps
keydown
businessworks
qcombobox
smartcontracts
network-flow
typescript1.8
nativeapplication
tactic
mediaelement
messenger
gridpane
libpng
underscore.js-templating
measures
player
multiple-regression
lttng
angstrom-linux
pagedlist
skype4py
ready-api
xpath-1.0
unity-networking
python-3.2
mono-embedding
fluid-dynamics
e10s
device-orientation
knuth
cctv
preferences
neolane
rtmfp
balanced-payments
html5-notifications
prettify
terminal-services
listings
angularjs-controller
quickdialog
funscript
frameset
removeclass
adk
coercion
xmlspy
xmemcached
disclosure
subviews
zend-decorators
procedural-music
django-notification
signal-handling

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