Hello i am new to STAX and I have xml file as an example. Like this
<?xml version="1.0"?>
<data>
<name>
<sensitive>true</sensitive>
</name>
<dob>
<sensitive>false</sensitive>
</dob>
<email-id>
<sensitive>true</sensitive>
</email-id>
<ssn>
<sensitive>true</sensitive>
</ssn>
<bankaccountnumber>
<sensitive>true</sensitive>
</bankaccountnumber>
<licencenumber>
<sensitive>false</sensitive>
</licencenumber>
I want just feild name , whose sensitive value is true. In this example i want just Name,ssn, emailid and bankaccount number. So how can i do. Please anyone help me.
It is much more easier to use DOM. You can refer here : http://www.developerfusion.com/code/2064/a-simple-way-to-read-an-xml-file-in-java/ . Hope can help you
Use dom4j. Here is sample code that may help you :
private List<String> _listXPath = new ArrayList<String>();
public static void main(String[] args) {
Document document = DocumentHelper.parseText(xml);
treeWalk(document);
}
private void treeWalk(Document document) {
treeWalk( document.getRootElement() );
}
// Traverse xml
private void treeWalk(Element element) {
String line = "";
for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
Node node = element.node(i);
if ( node instanceof Element ) {
Element el = (Element) node;
for ( int j = 0, total = el.attributeCount(); j < total; j++ ) {
Attribute attribute = el.attribute(j);
line = attribute.getPath() + attribute.getValue();
_listXPath.add(line);
}
treeWalk( (Element) node );
}
else {
line = node.getPath() +node.getText();
_listXPath.add(line);
}
}
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a flat file directory structure stored in a csv file which contains
id; parentId; name; type; size; classification; checksum;
1;3;file1;file;10;Secret;42;
2; ;folder2;directory; ; ; ;
3;11;folder3;directory; ; ; ;
4;2;file4;file;40;Secret;42;
5;3;file5;file;50;Public;42;
6;3;file6;file;60;Secret;42;
7;3;file7;file;70;Public;42;
8;10;file8;file;80;Secret;42;
9;10;file9;file;90;Top secret;42;
10;11;folder10;directory; ; ; ;
11;2;folder11;directory; ; ; ;
we need to arrange the structure as tree hierarchy by using id and parent id. I am able to do it manually where
it showed in the figure. But when it comes to coding i am not able to find exact solution using correct data structure.
the output should be in the form of root folder to base folder or files when printing the folder it should print the
size of the files and folders in that folder. An appropriate java or python solution will be helpful
name = folder2, type = Directory, size = 400
name = file4, type = File, size = 40, classification = Secret, checksum = 42
name = folder11, type = Directory, size = 360
name = folder10, type = Directory, size = 170
name = file8, type = File, size = 80, classification = Secret, checksum = 42
name = file9, type = File, size = 90, classification = Top secret, checksum = 42
name = folder3, type = Directory, size = 190
name = file1, type = File, size = 10, classification = Secret, checksum = 42
name = file5, type = File, size = 50, classification = Public, checksum = 42
name = file6, type = File, size = 60, classification = Secret, checksum = 42
name = file7, type = File, size = 70, classification = Public, checksum = 42
Here is a very basic Java implementation.
HashMap<String, Set<String>> nodes = new HashMap<>();
File file = new File("E:/test.txt");
try (Stream<String> stream = Files.lines(file.toPath())) {
stream.forEach((line) -> {
String parts[] = line.split(";");
nodes.putIfAbsent(parts[0], new HashSet<>());
nodes.putIfAbsent(parts[1], new HashSet<>());
nodes.get(parts[1]).add(parts[0]);
});
} catch (Exception e) {
e.printStackTrace();
}
The above code maps children files to their parents. This is a lazy method of implementing a tree wherein you know about all of the nodes and their children, which is all information presented in the flat file directory structure. It streams the file line by line; at each line it takes the node id and parent id, creates nodes for either of them if they don't exist before adding the node id to the parent id children set.
The node HashMap looks like this at this stage:
{ =[2], 11=[3, 10], 1=[], 2=[11, 4], 3=[1, 5, 6, 7], 4=[], 5=[], 6=[], 7=[], 8=[], 9=[], 10=[8, 9]}
If you are happy with treating the " " String as the root, you can begin recursively traversing through the list by retrieving the root nodes.get(" ");, otherwise you will need to define how you retrieve the root node.
One potential way of adopting this approach while maintaining the information is to treat each File as a Node.
public static void main (String args[]) {
HashMap<Node, Set<Node>> nodes = new HashMap<>();
File file = new File("E:/test.txt");
try (Stream<String> stream = Files.lines(file.toPath())) {
stream.forEach((line) -> {
String parts[] = line.split(";");
Node node = new Node(parts);
Node parent = new Node(parts[1]);
nodes.putIfAbsent(parent, new HashSet<>());
nodes.putIfAbsent(node, new HashSet<>());
nodes.get(parent).add(node);
});
} catch (Exception e) {
e.printStackTrace();
}
calculateSize(nodes, new Node(" "));
traverse(nodes, new Node(" "));
}
public static void traverse(HashMap<Node, Set<Node>> nodes, Node root) {
System.out.println(root);
for (Node child : nodes.get(root)) {
traverse(nodes, child);
}
}
public static int calculateSize(HashMap<Node, Set<Node>> nodes, Node root) {
int size = root.getSize();
for (Node child : nodes.get(root)) {
size += calculateSize(nodes, child);
}
root.setSize(size);
return size;
}
public static class Node {
private String id = " ";
private String type= " ";
private String name = " ";
private int size = 0;
private String classification = " ";
private int checksum = 0;
public Node (String[] parts) {
this.id = parts[0];
this.name = parts[2];
this.type = parts[3];
this.classification = parts[5];
if (this.type.equals("file")) {
this.size = Integer.parseInt(parts[4]);
this.checksum = Integer.valueOf(parts[6]);
}
}
public Node (String id) {
this.id = id;
}
#Override
public String toString() {
if (name.equals(" ")) return "Root";
String toString = (name.equals(" ")) ? "" : String.format("name = %s", name);
toString += (type.equals(" ")) ? "" : String.format(", type = %s", type);
toString += String.format(", size = %d", size);
toString += (classification.equals(" ")) ? "" : String.format(", classification = %s", classification);
toString += String.format(", checksum = %d", checksum);
return toString;
}
#Override
public boolean equals(Object o) {
if (o instanceof Node) {
return ((Node) o).id.equals(this.id);
} else if (o instanceof String) {
return o.equals(this.id);
}
return false;
}
#Override
public int hashCode() {
return this.id.hashCode();
}
public int getSize() { return size; }
public void setSize(int size) { this.size = size; }
}
The recursive search allows you to traverse through the nodes and print them to console. Note I've overriden the equals, hashCode and toString methods. The equals and hashCode allow you to avoid duplicates and ensure node association is retained.
If you're wanting to sum the files up, you can, as I have suggested, use recursion to calculate the sum for a specific directory and all it's children.
Your question is extremely unclear as to what you want. Please be more clear next time.
As a side note: You're diagram is incorrect. 7 is only a sub-directory of 3, not 10.
You could make 2 classes File and Folder where you can override the __str__() method in those classes to what you need.
I have an XML file and I want to read all the child nodes / tags values for the given Parent tag.
Sample XML content:
<ns2:customerSummary>
<ns2:address>
<ns2:city>SOUTH CHESTERFIELD</ns2:city>
<ns2:country>USA</ns2:country>
<ns2:isoCountryCode>US</ns2:isoCountryCode>
<ns2:line1>9998, N. MICHIGAN ROAD.</ns2:line1>
<ns2:postalCode>23834</ns2:postalCode>
<ns2:state>VA</ns2:state>
</ns2:address>
<ns2:allowPasswordChange>true</ns2:allowPasswordChange>
<ns2:arpMember>false</ns2:arpMember>
<ns2:brandCode>RCI</ns2:brandCode>
<ns2:brandId>1</ns2:brandId>
<ns2:companyCode>RCI</ns2:companyCode>
<ns2:eliteMemberRewardStatus>false</ns2:eliteMemberRewardStatus>
<ns2:eliteRewardStatus>true</ns2:eliteRewardStatus>
<ns2:europePointsClubMember>false</ns2:europePointsClubMember>
<ns2:firstName>FRANK</ns2:firstName>
<ns2:homePhone>804/733-3004</ns2:homePhone>
<ns2:isoCurrencyCode>USD</ns2:isoCurrencyCode>
<ns2:isoLanguageCode>EN</ns2:isoLanguageCode>
<ns2:language>EN</ns2:language>
<ns2:lastName>BROWNING B</ns2:lastName>
<ns2:locale>en_US</ns2:locale>
For example, if I provide the tag like "ns2:customerSummary" as parent tag it should return all the siblings / child nodes and their data Or if the parent tag is "ns2:address" it should return like city, country etc.
I have tried like this but, it takes from the top level.
public static void getAllChildTags(String strXmlFile, String strParentTag) {
String strXmlFileName = System.getProperty("user.dir") + File.separator + "\\resources\\customers.xml";
String tagName = "ns2:customerSummary";
// Parse Xml File
parseXmlFile(strXmlFileName);
//get the root element
Element docEle = dom.getDocumentElement();
Node childNode = docEle.getFirstChild();
while (childNode.getNextSibling() != null)
{
childNode = childNode.getNextSibling();
if (childNode.getNodeType() == Node.ELEMENT_NODE)
{
Element childElement = (Element) childNode;
System.out.println("Node -> " + childElement.getNodeName() + " Value -> " + childElement.getNodeValue());
}
}
}
I got the logic and wrote the script for fetching all the child elements data based on the given parent tag. Look at this.
// This method returns all the child elements of the given Parent tag
public static void getAllChildTags(String strXmlFile, String strParentTag) {
// Parse Xml File
parseXmlFile(strXmlFile);
NodeList flowList = dom.getElementsByTagName(strParentTag);
for (int i = 0; i < flowList.getLength(); i++)
{
NodeList childList = flowList.item(i).getChildNodes();
for (int j = 0; j < childList.getLength(); j++)
{
Node child = childList.item(j);
if (!child.getNodeName().equals("#text"))
{
System.out.println(child.getNodeName() + " -> " + childList.item(j).getTextContent());
}
}
}
}
Thanks,
I’m developing a companion bot for dementia suffers able to record, store and integrate memories into conversation. The bot calls an xml. file for conversations which can detect contexts passing an argument via baseContext.xml to call a topic.class and dynamically reload new xml data parser and bot while Main.class continues other tasks.
However, I can’t decide if trying to reload the parser/bot into JVM is feasible or whether pausing the class threads and calling a new class/es would be the best solution, or another solution is available. Ideally I’d like to pass the new xml data into the JVM while the other classes persist.
Any help much appreciated.
Main Class (calls the bot, camera, scheduler, text history etc)
public class Main extends javax.swing.JFrame {
private static Bot bot;
public BlockingQueue<String> queue;
public Main() {
initComponents();
//get the parser going
DataParser dp = new DataParser();
//make new bot with level 0 as default and given data parser
bot = new Bot("0", dp);
//dispaly the default message
txtHistory.setText("Bot: " + bot.getMessage());
}
public Main(BlockingQueue<String>queue) {
this.queue = queue;
}
// display bot response in the text area
private static final String VOICENAME="kevin16";
private static void addBotText(String message) {
txtHistory.setText(txtHistory.getText() + "\nBot: " + message);
//turn the bot response to sound
Voice voice;
VoiceManager vm= VoiceManager.getInstance();
voice=vm.getVoice(VOICENAME);
voice.allocate();
try{
voice.speak(bot.getMessage());
}catch(Exception e){
}
voice.deallocate();
}
public static void listen (String speech) {
txtHistory.setText(txtHistory.getText() + "\nYou: " + speech + "\n");
//send the input to the bot and get bot response
The Data parser class deals with the xml loading into DOM
package bot;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DataParser {
private Document dom;
private HashMap<String, State> states = new HashMap<String, State>();
private ArrayList<String> invalidMessages = new ArrayList();
private int invalidMessageIndex = 0;
public int stateCounter = 1000;
public String fileSource;
// default constructor
public DataParser() {
// Load the XML file and parse it
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//get the filepath of source
String fileSource = Context.getSource();
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
dom = db.parse(fileSource);
// Load configuration and states from the XML file
loadConfiguration();
loadStates();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (SAXException se) {
se.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
// Load states from XML file
private void loadStates() {
// get document element object
Element docEle = dom.getDocumentElement();
// get all State node names
NodeList nl = docEle.getElementsByTagName("State");
// if node is not null and has children
if (nl != null && nl.getLength() > 0) {
// loop through all children
for (int i = 0; i < nl.getLength(); i++) {
// get state element
Element el = (Element) nl.item(i);
// get state id
String id = el.getAttribute("id");
// get all state messages
ArrayList messages = new ArrayList();
NodeList messagesNodeList = el.getElementsByTagName("message");
// if messages node is not null and has children
if (messagesNodeList != null && messagesNodeList.getLength() > 0) {
// loop through all children
for (int j = 0; j < messagesNodeList.getLength(); j++) {
// get current message element
Element elmsg = (Element) messagesNodeList.item(j);
// append message node value to the messages list
messages.add(elmsg.getFirstChild().getNodeValue());
}
}
// get keywords in the current state
ArrayList keywords = getKeywords(el);
// construct a new State object
State state = new State(id, messages, keywords);
stateCounter ++;
// add the state to the states hashmap
states.put(id, state);
}
}
}
// get state object by id
public State getState(String id) {
return states.get(id);
}
// create a new state
public void addState(State state){
states.put(state.getId(), state);
stateCounter++;
}
// get all keywords in an State tag
public ArrayList getKeywords(Element ele) {
// construct keywords arraylist
ArrayList keywords = new ArrayList();
// get all nodes by keyword tag name
NodeList nl = ele.getElementsByTagName("keyword");
// if the tag is not null and has children
if (nl != null && nl.getLength() > 0) {
// loop through all the children
for (int i = 0; i < nl.getLength(); i++) {
//get the keyword element
Element el = (Element) nl.item(i);
// find the keyword target, classname and argument attributes
String wordTag = el.getFirstChild().getNodeValue();
String target = el.getAttribute("target");
String className = el.getAttribute("className");
String arg = el.getAttribute("arg");
String variable = el.getAttribute("variable");
int points = 0;
try{
points = Integer.valueOf(el.getAttribute("points"));
}catch (Exception e){
}
String learn = el.getAttribute("learn");
// split keyword by comma
String[] words = wordTag.split(",");
// loop through all words
for (String word : words) {
// trim the word to remove spaces
word = word.trim();
// construct a new keyword
Keyword keyword = new Keyword(word, target, className, arg, variable, points, learn );
// add the keyword to keywords array list
keywords.add(keyword);
}
}
}
// return all the keywords in the given node
return keywords;
}
// returns one of the invalid messages and move the index to the next message
public String getInvalidAnswer() {
// get current answer
String answer = invalidMessages.get(invalidMessageIndex);
// increase the index, if it is end of messages, reset the index to 0
invalidMessageIndex++;
if (invalidMessageIndex >= invalidMessages.size()) {
invalidMessageIndex = 0;
}
return answer;
}
// load cofig tags from data xml file
private void loadConfiguration() {
// get document element
Element docEle = dom.getDocumentElement();
// get all node names for invalid messages
NodeList node = docEle.getElementsByTagName("InvalidMessages");
// get all message nodes inside invalid messages node
NodeList nl = ((Element) node.item(0)).getElementsByTagName("message");
// if node is not null and has children
if (nl != null && nl.getLength() > 0) {
// loop through all children
for (int i = 0; i < nl.getLength(); i++) {
// get message node
Element el = (Element) nl.item(i);
// get message and add it to invalid messages array
String message = el.getFirstChild().getNodeValue();
invalidMessages.add(message);
}
}
}
}
The bot class manages conversation and calls specialised classes.
package bot;
import smallTalk.Morning;
import smallTalk.Afternoon;
import smallTalk.Evening;
import smallTalk.Night;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Bot {
// Store all regular expression matches
private HashMap<String,String> dictionary;
// Default state to start the bot
String level = "0";
DataParser parser;
// default constructor
public Bot(String level, DataParser parser) {
dictionary = new HashMap<String,String>();
this.level = level;
this.parser = parser;
}
// get current state message
public String getMessage() {
State state = parser.getState(level);
return replaceMatches(state.getMessage()).trim();
}
// send user message to the bot and get the response
public String send(String message) {
String response = "";
State state = parser.getState(level);
// end of the tree
if (state.getKeywords().isEmpty()) {
this.level = "0";
}
// match the keyword with given message
Keyword match = parse(message, state.getKeywords());
// if no keyword is matched, display one of the invalid answers
if (match == null) {
response = parser.getInvalidAnswer();
} else {
// if match classname is provided, check to get the dynamic response
if (match.className.length() > 0) {
// check for Weather dynamic response
if (match.className.equals("Weather")) {
Weather weather = new Weather();
response = weather.getResponse(match.arg);
this.level = "0";
}
// check for News dynamic response
else if (match.className.equals("News")) {
News news = new News();
response = news.getResponse(match.arg);
this.level = "0";
}
else if (match.className.equals("Morning")) {
Morning morning = new Morning();
morning.wakeup();
}
else if (match.className.equals("Afternoon")) {
Afternoon afternoon = new Afternoon();
afternoon.midday();
}
else if (match.className.equals("Evening")) {
Evening evening = new Evening();
evening.dinner();
}
else if (match.className.equals("Night")) {
Night night = new Night();
night.late();
}
// check for Topic dynamic response
else if (match.className.equals("Topic")) {
Topic topic = new Topic();
topic.getTopic(match.arg);
}
} else {
// get the new state and return the new message
if (response.length() == 0) {
this.level = match.target;
state = parser.getState(level);
// if it is end of the tree
if (state.getKeywords().isEmpty()) {
response = this.getMessage();
this.level = "0";
}
}
}
}
return response;
}
// parse the given text to find best match in the keywords
private Keyword parse(String text, ArrayList<Keyword> keylist) {
// set the default match to none
int bestMatch = -1;
Keyword match = null;
// loop through keywords
for (int i = 0; i < keylist.size(); i++) {
// get number of matches of the keyword with given text
int matches = getMatches(text, keylist.get(i));
// if match is better than best match, replace it
if (matches > -1 && matches > bestMatch) {
match = keylist.get(i);
bestMatch = matches;
}
}
// add best answers regex variable value into the dictionary for future reference
if (match != null){
if(match.learn.length() > 0 ){
// get training data keyword and description
String subject = dictionary.get(match.learn);
String result = match.variableValue;
// create a new state for new trained data
ArrayList<String> messages = new ArrayList<String>();
messages.add(result);
State myState = new State(String.valueOf(parser.stateCounter),messages,new ArrayList());
parser.addState(myState);
// add the new trained keyword
Keyword keyword = new Keyword(subject, myState.getId(), "", "", "", 1, "" );
State state = parser.getState("1");
ArrayList<Keyword> keywords = state.getKeywords();
keywords.add(keyword);
}else{
if (match.variableValue.length() > 0){
dictionary.put(match.variable, match.variableValue);
}
}
}
return match;
}
// get number of matches of the given keywords in the given list
private int getMatches(String text, Keyword keyword) {
// no match by default
int result = -1;
// return 0 match when keyword is *
if(keyword.keyword.equals("*")){
return keyword.points;
}
// if regex is expected
if(keyword.variable.length() > 0){
String match = Regex.match(keyword.keyword, text);
if(match.length() > 0){
keyword.variableValue = match;
return keyword.points;
}
}
String[] words = keyword.keyword.split(" ");
// loop through list of the keywords
for (String word : words) {
// if current keyword is in the text, add points
if (text.toLowerCase().indexOf(word.toLowerCase()) >= 0) {
result = result + keyword.points + 1;
} else {
// return null if one of the keywords does not exists
return -1;
}
}
return result;
}
// replace given text with variables in the dictionary
public String replaceMatches(String text){
// replace variables within dictionary in the text
for (Map.Entry<String, String> entry : dictionary.entrySet()) {
text = text.replaceAll("\\["+entry.getKey() + "\\]", entry.getValue());
}
// remove empty variables tags
return Regex.clear(text);
}
}
The Context class passes the xml file source to data parser.
package bot;
public class Context {
public static String source = "newcontext.xml";
//method to get value of source called in dataParser
public static String getSource(){
return source;
}
//get the new topic from Topic Class and prepare to reload DataParser/Bot
public static void newSource(String currentTopic){
source = currentTopic;
}
}
After I run the method, it just loops through and prints the entire array and the contents in that index.
Wondering what I am doing wrong and how to make it only print out the array information that is the lowest melting point.
public void choiceFive() {
double smaller = elementArray[0].getMeltingPoint();
for(int i = 0; i < count; i++){
if(elementArray[i].getMeltingPoint() < smaller){
smaller = elementArray[i].getMeltingPoint();
}
System.out.println(smaller);
}
}
I assume you have an Element class with name, meltingPoint, and some other properties and you want to find the lowest melting point of an elementArray.
Get lowest melting point:
I implemented a method which returns the LowestMeltingPoint element:
If elementArray is null or it's empty return null.
Set the first element as currentLowestMeltingPoint (because it is so far).
Loop through the array using forEach (which is pretty more clean) and check if the element melt point is lower than the current. If it's true: set the element to currentLowestMeltingPoint, otherwise keep the iteration.
Note: It will also print the current lowest with informational purposes.
Element Class:
public class Element
{
private String name;
private double meltingPoint;
public Element ( String name , double meltingPoint )
{
super ( );
this.name = name;
this.meltingPoint = meltingPoint;
}
public String getName ( )
{
return name;
}
public void setName ( String name )
{
this.name = name;
}
public double getMeltingPoint ( )
{
return meltingPoint;
}
public void setMeltingPoint ( double meltingPoint )
{
this.meltingPoint = meltingPoint;
}
#Override
public String toString ( )
{
return "Element [name=" + name + ", meltingPoint=" + meltingPoint + "]";
}
}
Main Program:
public class MainProgram
{
/**
* Main method to test getLowestMeltingPoint method
* #param args
*/
public static void main ( String [ ] args )
{
Element helium = new Element ( "Helium" , -272 );
Element radon = new Element ( "Radon" , -71 );
Element mercury = new Element ( "Mercury" , -39 );
Element sulfur = new Element ( "Sulfur" , 113 );
Element polonium = new Element ( "Polonium" , 254 );
Element[] elementArray = {mercury, sulfur, radon, polonium, helium};
Element lowestMeltingPointE = getLowestMeltingPoint ( elementArray );
System.out.println ( "----------------------------------------------" );
System.out.println ( "My lowest melting point is: " + lowestMeltingPointE.getName ( ));
System.out.println ( "Its melting point is: " + lowestMeltingPointE.getMeltingPoint ( ) );
System.out.println ( "element toString: " + lowestMeltingPointE.toString ( ) );
}
/**
* this method finds the lowest melting point element
* #param elementArray, which is the element array you want to compare
* #return element with lowest point or null if array is null or empty
*/
public static Element getLowestMeltingPoint( Element[] elementArray)
{
Element currentLowest;
if( elementArray == null || elementArray.length == 0)
{
return null;
}
else
{
currentLowest = elementArray[0];
}
for ( Element element : elementArray)
{
if ( element.getMeltingPoint ( ) < currentLowest.getMeltingPoint ( ) )
{
currentLowest = element;
}
System.out.println ( "Current lowest: " + currentLowest.toString ( ) );
}
return currentLowest;
}
}
Note: The method is static. If you don't know what it is check: Understanding Class Members
Output:
Current lowest: Element [name=Mercury, meltingPoint=-39.0]
Current lowest: Element [name=Mercury, meltingPoint=-39.0]
Current lowest: Element [name=Radon, meltingPoint=-71.0]
Current lowest: Element [name=Radon, meltingPoint=-71.0]
Current lowest: Element [name=Helium, meltingPoint=-272.0]
----------------------------------------------
My lowest melting point is: Helium
Its melting point is: -272.0
element toString: Element [name=Helium, meltingPoint=-272.0]
I just wanted to give you the full answer, because there are a lot of resources out there and when i was starting on Java i wasn't aware of.
Good Luck!
You have to move System.out.println(smaller); outside the for loop. Otherwise you keep printing it.
move the print into the if block
if(elementArray[i].getMeltingPoint() < smaller){
smaller = elementArray[i].getMeltingPoint();
System.out.println(smaller);
}
or after processing has completed
for(int i = 0; i < count; i++){
if(elementArray[i].getMeltingPoint() < smaller){
smaller = elementArray[i].getMeltingPoint();
}
}
System.out.println(smaller);
You can change
for(int i = 0; i < count; i++)
to
for(int i = 0; i < elementArray.length; i++)
and move the print statement outside the loop in order to print the lowest melting point amongst all.
for(int i = 0; i < elementArray.length; i++) {
if(elementArray[i].getMeltingPoint() < smaller){
smaller = elementArray[i].getMeltingPoint();
}
}
System.out.println(smaller);
i'm a beginner in java and XML , but I have a task to perform and I don't know how to use a recursive function which uses Element.
I made this program.
public class JDOM2
{
private static final String xmlroutes = "C://Users//Thomas//Desktop//routes.xml";
static Element root;
public static void main(String[] args) throws JDOMException, IOException
{
// the SAXBuilder is the easiest way to create the JDOM2 objects.
SAXBuilder jdomBuilder = new SAXBuilder();
// jdomDocument is the JDOM2 Object
Document jdomDocument = jdomBuilder.build(xmlroutes);
root = jdomDocument.getRootElement();
List <Element> location_properties = root.getChildren("LOCATION_PROPERTIES");
Iterator<Element> it = location_properties.iterator();
Element loc = it.next();
rootiteration();
}
public static void rootiteration()
{
int time;
List <Element> location_properties = root.getChildren("LOCATION_PROPERTIES");
Iterator<Element> it = location_properties.iterator();
Element loc = it.next();
if(loc.getAttributeValue("NAME").startsWith("STN")== true)
{
List <Element> segment_properties = loc.getChildren("SEGMENT_PROPERTIES");
Iterator<Element> it2 = segment_properties.iterator();
Element seg = it2.next();
List <Element> next_location = seg.getChildren("NEXT_LOCATION");
for (Element next: next_location)
{
if(next.getAttributeValue("NAME").startsWith("STN")== true)
{
System.out.print("Arrival : " +next.getAttributeValue("NAME"));
int L = Integer.parseInt(next.getAttributeValue("LENGTH"));
int S = Integer.parseInt(next.getAttributeValue("SPEED"));
time = L/S;
System.out.println(" --- Time to go : "+time+" seconds");
}
if(next.getAttributeValue("NAME").startsWith("STN")== false)
{
recursive(); // I think the problem is here but I may have done some other mistakes.
}
}
}
}
public static int recursive(Element parent, int t0, Element child) throws IOException
{
List <Element> location_properties = root.getChildren("LOCATION_PROPERTIES");
Iterator <Element> i = location_properties.iterator();
int t1 = 0;
while (i.hasNext())
{
child = (Element) i.next();
int L = Integer.parseInt(child.getChild("SEGMENT_PROPERTIES").getChild("NEXT_LOCATION").getAttributeValue("LENGTH"));
int S = Integer.parseInt(child.getChild("SEGMENT_PROPERTIES").getChild("NEXT_LOCATION").getAttributeValue("SPEED"));
t1 = L/S;
//t1 = time_between();
if (child.getAttributeValue("NAME").startsWith("STN")== true)
{
System.out.println("From : "+parent+" to "+child+" --- Time to go : "+t1+" seconds");
System.out.println(child.getAttributeValue("NAME"));
System.out.println(parent);
}
if (child.getAttributeValue("NAME").startsWith("X")== true) // child is not STN, recurse
{
recursive(parent, t0 + t1,child);
System.out.println("From : "+parent+" to "+child+" --- Time to go : "+t1+" seconds");
// t0 = t0 + t1;
}
}
return t0;
}
This is supposed to calculate the time between 2 Elements. King of this way :
I need two functions, one which iterates over all root elements, and starts the tree traversal at a starting STN, and a recursive function that traverse the tree until it finds an ending STN.
To have something like that :
Departure Station : STN10
Arrival : X535 --- Time to go : 16 seconds
Arrival : X536 --- Time to go : 2 seconds
Arrival : X537 --- ...
Arrival : STN26 --- Total time to Station : ...
Departure Station : STN11
Arrival : X535 ---
...And so on.
I think you can change the second method as follows and it would work:
public static int recursive(Element root, int t0, Element current) throws IOException
{
List <Element> location_properties = current.getChildren("LOCATION_PROPERTIES");
Iterator <Element> i = location_properties.iterator();
int t1 = 0;
while (i.hasNext())
{
child = (Element) i.next();
int L = Integer.parseInt(child.getChild("SEGMENT_PROPERTIES").getChild("NEXT_LOCATION").getAttributeValue("LENGTH"));
int S = Integer.parseInt(child.getChild("SEGMENT_PROPERTIES").getChild("NEXT_LOCATION").getAttributeValue("SPEED"));
t1 = L/S;
//t1 = time_between();
if (child.getAttributeValue("NAME").startsWith("STN")== true)
{
System.out.println("From : "+root+" to "+child+" --- Time to go : "+t1+" seconds");
System.out.println(child.getAttributeValue("NAME"));
}
if (child.getAttributeValue("NAME").startsWith("X")== true) // child is not STN, recurse
{
recursive(root, t0 + t1, child);
}
}
return t0;
}
Everytime a non-STN element is encountered the child element will be passed to the recursive method as the current element.
You will have to call this method using the root element as the root parameter and the same element as the current parameter. i.e., recursive(root, 0, root).
Please note that I could not test this as the xml file is not accessible to me. Hope this helps.
For those who can be interested, I used this function to re-use the string "next.getAttributeValue("NAME")" as an element.
public static Element getElembyName(final String name){
List <Element> location_properties = root.getChildren("LOCATION_PROPERTIES");
for (Element loc : location_properties)
{
if(loc.getAttributeValue("NAME").equals(name))
return loc;
}
return null;
}