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

what's the meaning of “4” from Imgproc.COLOR_HSV2RGB_FULL, 4);?
Hibernate JPA, Problems adding data to a many to many table
how to get first word before spacing from text file java?
Wrap criteria query with count JPA 2.0 with hibernate vendor
WebDriver - Check Forgot password functionality using selenium
paste embedded link to textbox
Not able to Load Image from Server in android
Why does Map<> m = new HashMap<String, String>() not compile? [on hold]
Maven testCompile works with Java 9 Build 166, but fails with Build 167
Use of Private static
how to further debug to expose the values in the element in groovy script
Log4j 1.x Sentry appender: suppress warnings from specific sources for one appender
Reading a properties file that is OUTSIDE a jar file
mysql jdbc driver and java project
java DOM XML Parser Inner Element
Loading classes dynamically in osgi bundle running in karaf runtime

Categories

HOME
vim
date
proxy
azure-data-factory
kde
mfc
lodash
react-redux
youtube-api-v3
baqend
blueprintjs
metatrader4
wheelnav.js
zebra-printers
percona
vaadin7
lombok
progressive-web-apps
propel
oracle-coherence
nhibernate-envers
kryo
ehcache
captiveportal
vlsi
sparse-matrix
centos6.5
intel-pin
internet-explorer-9
entitlements
rst2pdf
preg-match
yadcf
webtest
lxd
asset-pipeline
repo
openoffice.org
gammu
geopositioning
host
theano.scan
opshub
ruby-on-rails-3.1
reportingservices-2005
botbuilder
spring-security-kerberos
password-encryption
bootstrap-dialog
auto-update
chain-builder
revapi
qsslsocket
worksheet
return-value
idisposable
android-cursor
np-complete
boost-preprocessor
knpmenubundle
orthogonal
chord-diagram
eventkit
setuptools
mikroc
master-slave
tform
revolution-r
asp.net5
cloudbees
freedesktop.org
django-unittest
service-accounts
sysinternals
composite
inmobi
geonetwork
coldbox
codeigniter-routing
html-helper
responsive-slides
typeof
starcluster
yorick
didselectrowatindexpath
resty-gwt
blending
ruby-datamapper
file-locking
ora-00911
xamlparseexception
clipper
ohm
gwt-ext
ecl
sproutcore-2
revisions
nhibernate.search
user-friendly
webkit.net
photoshop-cs4
geneva-server

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App