Okay so I'm creating a users class which asks for input then stores it in an XML file using java. I figured out to create the original XML file I think but I'm have trouble figuring out how to add a new user with the attribute "id" of one more then the previous User entry.
Here is the code I have so far:
/*imports */
public class CreateUser {
static Scanner input = new Scanner(System.in);
/* object names*/
String name;
String age;
String bday;
String gender;
String location;
String orientation;
String relationship;
String hobbies;
String choice;
String username;
String password;
public void makeUser(){
/*left out code to get user entries here
seemed irrelevant/*
/*checks for file if it doesn't exist then it creates it else it should append
the user to the xml document with a id increase of one.
The appending part I'm not sure how to do.*/
File f = new File("C:\\Users\\Steven\\Workspace\\twitter\\src\\users.xml");
if(f.exists()) {
try {
/* need help here*/
}
}
else{
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document users = docBuilder.newDocument();
Element user = users.createElement("user");
users.appendChild(user);
Attr attr = users.createAttribute("id");
attr.setValue("0");
user.setAttributeNode(attr);
Element dname = users.createElement("name");
dname.appendChild(users.createTextNode(name));
user.appendChild(dname);
Element dgender = users.createElement("gender");
dgender.appendChild(users.createTextNode(gender));
user.appendChild(dgender);
Element dlocation = users.createElement("location");
dlocation.appendChild(users.createTextNode(location);
user.appendChild(dlocation);
Element dorientation = users.createElement("orientation");
dorientation.appendChild(users.createTextNode(orientation));
user.appendChild(dorientation);
Element drelationship = users.createElement("relationship");
drelationship.appendChild(users.createTextNode(relationship));
drelationship.appendChild(drelationship);
Element dhobbies = users.createElement("hobbies");
dhobbies.appendChild(users.createTextNode(hobbies));
dhobbies.appendChild(dhobbies);
Element dchoice = users.createElement("choice");
dchoice.appendChild(users.createTextNode(choice));
dchoice.appendChild(dchoice);
Element dusername = users.createElement("username");
dusername.appendChild(users.createTextNode(username));
dusername.appendChild(dusername);
Element dpassword = users.createElement("password");
dpassword.appendChild(users.createTextNode(password));
dpassword.appendChild(dpassword);
Element dbday = users.createElement("birthday");
dbday.appendChild(users.createTextNode(bday));
dbday.appendChild(dbday);
Element dage = users.createElement("age");
dage.appendChild(users.createTextNode(age));
dage.appendChild(dage);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(users);
StreamResult result = new StreamResult(new File("C:\\Users\\Steven\\Workspace\\twitter\\src\\users.xml"));
StreamResult test = new StreamResult(System.out);
transformer.transform(source, result);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
I know its a lot of code to look through and I don't want an exact coded answer but maybe just how to append the user with the attribute value one more then the previous entry. Or a point in a the direction of a helpful website. Anything really I've been perplexed for a little and I feel like I should get something this simple. Thanks in advance for any help
In your first section(if block), I think you can open your file in append mode as below to add an user, assuming user node is not wrapped in another node.
StreamResult result = new StreamResult(
new FileWriter("C:\\Users\\Steven\\Workspace\\twitter\\src\\users.xml", true));
There are two changes in above statement:
Using FileWriter in place of File
Using a second parameter true, which open the file in append mode.
EDIT: To get the max existing ID, you need to read file and look for ID tag as below:
File xmlFile = new File("C:\\Users\\Steven\\Workspace\\twitter\\src\\users.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("userId");//use the id tag name
int maxId = 0;
for(Node node: nList){
if(Integer.parseInt(node.getTextContent()) > maxId ){
maxId = Integer.parseInt(node.getTextContent());
}
}
int newId = maxId +1; //use this ID
xmlFile.close();//close the file
Consider JAXB, here is a working example to start with:
static class Users {
private List<User> user = new ArrayList<>();
public List<User> getUsers() {
return user;
}
public void setUsers(List<User> users) {
this.user = users;
}
}
static class User {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static void main(String[] args) throws Exception {
User user = new User();
user.setName("user1");
Users users = new Users();
users.setUsers(Arrays.asList(user));
JAXB.marshal(users, new File("users.xml"));
users = JAXB.unmarshal(new File("users.xml"), Users.class);
User user2 = new User();
user2.setName("user2");
users.getUsers().add(user2);
JAXB.marshal(users, System.out);
}
Consider SAX, unlike DOM it's fast and has no size limit. Here's a basic example:
public static void main(String[] args) throws Exception {
String xml = "<users><user><name>user1</name></user></users>";
XMLReader xr = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("users")) {
addUser();
}
super.endElement(uri, localName, qName);
}
private void addUser() throws SAXException {
super.startElement("", "", "user", null);
addFileld("name", "user2");
super.endElement("", "", "user");
}
private void addFileld(String name, String value) throws SAXException {
super.startElement("", "", name, null);
super.characters(value.toCharArray(), 0, value.length());
super.endElement("", "", name);
}
};
Source src = new SAXSource(xr, new InputSource(new StringReader(xml)));
Result res = new StreamResult(System.out);
TransformerFactory.newInstance().newTransformer().transform(src, res);
}
output:
<users><user><name>user1</name></user><user><name>user2</name></user></users>
Related
I'm trying to store an ArrayList into an XML file so that I can retrieve the information later on and then display it back into the console.
Can someone show me the most effective way to do this?
EDIT:
Heres what I am trying to write into an external file
// new user is created
Bank bank = new Bank();
System.out.println("Enter your full name below (e.g. John M. Smith): ");
String name = scanner.nextLine();
System.out.println("Create a username: ");
String userName = scanner.nextLine();
System.out.println("Enter your starting deposit amount: ");
int balance = scanner.nextInt();
System.out.print(dash);
System.out.print("Generating your information...\n");
System.out.print(dash);
int pin = bank.PIN();
String accountNum = bank.accountNum();
User user = new User(name, userName, pin, accountNum, balance);
//new user gets added to the array list
Bank.users.add(user);
System.out.println(user);
This all creates a Bank user, which gets thrown into an ArrayList, then I want to store their information so that I can come back later and redisplay it.
public static void main(String[] args) {
// TODO Auto-generated method stub
WriteFile ob = new WriteFile();
ArrayList list = new ArrayList();
list.add(new details("A", 20, 1));
list.add(new details("B", 30, 2));
ob.writeXmlFile(list);
}
// Modify this below class as per your need
class details {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
int age;
int id;
public details() {
}
public details(String name_, int age_, int id_) {
name = name_;
age = age_;
id = id_;
}
// below class actually writed
public void writeXmlFile(ArrayList<details> list) {
try {
DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
DocumentBuilder build = dFact.newDocumentBuilder();
Document doc = build.newDocument();
Element root = doc.createElement("Studentinfo");
doc.appendChild(root);
Element Details = doc.createElement("Details");
root.appendChild(Details);
for (details dtl : list) {
Element name = doc.createElement("Name");
name.appendChild(doc.createTextNode(String.valueOf(dtl
.getName())));
Details.appendChild(name);
Element id = doc.createElement("ID");
id.appendChild(doc.createTextNode(String.valueOf(dtl.getId())));
Details.appendChild(id);
Element mmi = doc.createElement("Age");
mmi.appendChild(doc.createTextNode(String.valueOf(dtl.getAge())));
Details.appendChild(mmi);
}
// Save the document to the disk file
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
// format the XML nicely
aTransformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
aTransformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
try {
// location and name of XML file you can change as per need
FileWriter fos = new FileWriter("./ros.xml");
StreamResult result = new StreamResult(fos);
aTransformer.transform(source, result);
} catch (IOException e) {
e.printStackTrace();
}
} catch (TransformerException ex) {
System.out.println("Error outputting document");
} catch (ParserConfigurationException ex) {
System.out.println("Error building document");
}
}
The way I do it is either using XStream or Jackson API (preferred) to serialize the java object to either a XML or a JSON file.
For example, see my XStream data provider I wrote for use with TestNG or JUnit parameterized tests.
How about using XMLEncoder/XMLDecoder?
http://docs.oracle.com/javase/6/docs/api/java/beans/XMLEncoder.html
Copy and paraphrasing from the javadoc.
ArrayList arr = new ArrayList();
// populate your array
XMLEncoder e = new XMLEncoder(BufferedOutputStream(
new FileOutputStream("Test.xml")));
e.writeObject(arr);
e.close();
Similarly, the reverse to decode.
Here you can see my application:
So what i need to do:
I dont know how I can through code link xml schema with JTable with all type(int,string,float). Say like Year is type int and in schema is int and how i can link it? I dont know how will be in english link or relate.
In this application i write all data to xml file, and when application loaded it loads all data from xml file.
Here i creating xml schema:
public void CreateSchema(String FileName){
file=FileName;
JAXBContext jc;
try {
jc = JAXBContext.newInstance(XmlSchemaType.class);
jc.generateSchema(new SchemaOutputResolver() {
#Override
public javax.xml.transform.Result createOutput(String namespaceURI, String suggestedFileName)throws IOException {
suggestedFileName=file+".xsd";
return new StreamResult(suggestedFileName);
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
}
Here is all types:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "Auto")
public class XmlSchemaType {
row[] Row;
}
class row {
#XmlAttribute
byte ID;
#XmlElement
String VIN;
#XmlElement
String Make;
#XmlElement
String Model;
#XmlElement
int Year;
#XmlElement
String Description;
#XmlElement
float Cost;
}
Here is writing to xml file:
public void CreateXml(JTable tb,JTable tb2,String FileName){
try {
file=FileName;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Auto");
doc.appendChild(rootElement);
int i=0,j=0,k=0;
while (i<tb.getRowCount()){
j=0;
Element rows = doc.createElement("Row");
rootElement.appendChild(rows);
Attr attr = doc.createAttribute("id");
attr.setValue((i+1)+"");
rows.setAttributeNode(attr);
//Pirma lentele
while (j<tb.getColumnCount()-1){
Element element = doc.createElement(tb.getTableHeader().getColumnModel().getColumn(j).getHeaderValue()+"");
element.appendChild(doc.createTextNode(tb.getModel().getValueAt(i, j)+""));
rows.appendChild(element);
j++;
}
//Antra lentele
j=2;//pirmu lauku nereikia
while (j<tb2.getColumnCount()-1){
Element element2 = doc.createElement(tb2.getTableHeader().getColumnModel().getColumn(j).getHeaderValue()+"");
element2.appendChild(doc.createTextNode(tb2.getModel().getValueAt(i, j)+""));
rows.appendChild(element2);
if (j==2){
tb2.getModel().setValueAt(tb.getModel().getValueAt(i, 0),i,1);
}
j++;
}
i++;
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result;
try {
FileOutputStream fileOutputStream = null;
fileOutputStream = new FileOutputStream(
new File(file+".xml"));
result = new StreamResult(fileOutputStream);//new FileOutputStream(file+".xml"));
transformer.setOutputProperty(OutputKeys.INDENT, "yes");//new line... kad butu naujoje eiluteje
transformer.transform(source, result);
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
//file.renameTo(FileName+".xml");
}
And here loading my xml file:
public void PopulateDataSet(JTable tb,JTable tb2,String FileName){
file=FileName;
File f= new File(file+".xml");
if (f.exists()){
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(f);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Row");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
DefaultTableModel model = (DefaultTableModel) tb.getModel();
model.addRow(new Object[] { "", "","","","Delete" });
tb.getModel().setValueAt(eElement.getElementsByTagName("VIN").item(0).getTextContent(),temp, 0);
tb.getModel().setValueAt(eElement.getElementsByTagName("Make").item(0).getTextContent(),temp, 1);
tb.getModel().setValueAt(eElement.getElementsByTagName("Make").item(0).getTextContent(),temp, 2);
tb.getModel().setValueAt(eElement.getElementsByTagName("Year").item(0).getTextContent(),temp, 3);
tb.getModel().setValueAt("Delete",temp, 4);
DefaultTableModel model2 = (DefaultTableModel) tb2.getModel();
model2.addRow(new Object[] { (tb2.getRowCount()+1), "","","","Delete" });
tb2.getModel().setValueAt(eElement.getElementsByTagName("VIN").item(0).getTextContent(),temp, 1);
tb2.getModel().setValueAt(eElement.getElementsByTagName("Description").item(0).getTextContent(),temp, 2);
tb2.getModel().setValueAt(eElement.getElementsByTagName("Cost").item(0).getTextContent(),temp, 3);
tb2.getModel().setValueAt("Delete",temp, 4);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (!f.exists()){
CreateXml(tb,tb2,file);
CreateSchema(file);
}
}
But how to use xml shema with JTable, xml?
"Here is writing to xml file:" ---- "And here loading my xml file:"
Why are you using DOM to read and write the xml, when you are already using JAXB Mapping. If you are doing the mapping correctly 1, it's just a matter of using the Marshaller and Unmarshaller to write and read, respectively. Make sure to look at those API links yo see example usage. It's only around 5 lines of code to handle each operaion.
(1) Please see the JAXB tutorial for more info about JAXB mapping.
Also, you can just create your own AbstractTableModel and unmarshal and marshal straight to and from the table model. This is probably the most effective way to keep everything sync. Create a class Auto to represent each row, and a class AutoModel, that will be the root element in the xml document, as well as the TableModel for the JTable. Something like:
Auto class
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "Auto", propOrder = {
"id", "VIN", "Make", "Model", "Year", "Description", "Cost"
})
public class Auto {
#XmlElement(name = "id")
Integer id;
#XmlElement(name = "VIN")
String VIN;
#XmlElement(name = "Make")
String Make;
#XmlElement(name = "Model")
String Model;
#XmlElement(name = "Year")
Integer Year;
#XmlElement(name = "Description")
String Description;
#XmlElement(name = "Cost")
Float Cost;
// === DON'T FORGET YOUR GETTERS and SETTERS
}
AutoModel class
#XmlRootElement(name = "AutoList")
public class AutoModel extends AbstractTableModel {
String[] columnNames = {"VIN", "Make", "Model", "Year"};
#XmlElement(name = "Auto")
protected List<Auto> autos;
public AutoModel() {
autos = new ArrayList<Auto>();
}
#Override
public int getRowCount() {
return autos.size();
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
#Override
public boolean isCellEditable(int row, int col) {
return false;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Auto auto = autos.get(rowIndex);
Object value = null;
switch (columnIndex) {
case 0 : value = auto.getVIN(); break;
case 1 : value = auto.getMake(); break;
case 2 : value = auto.getModel(); break;
case 3 : value = auto.getYear(); break;
}
return value;
}
}
Test, using this xml file
<?xml version="1.0" encoding="UTF-8"?>
<AutoList>
<Auto>
<id>1</id>
<VIN>123456788910FASDE</VIN>
<Make>Mercedes</Make>
<Model>CL 550</Model>
<Year>2012</Year>
<Description>Hello World</Description>
<Cost>80000.00</Cost>
</Auto>
</AutoList>
import java.awt.Dimension;
import java.io.File;
import javax.swing.*;
import javax.xml.bind.*;
public class TestTableMarshall {
private static final String INPUT_FILE = "src/table/autos.xml";
private static final String OUTPUT_FILE = "src/table/autos1.xml";
public static void main(String[] args) throws Exception {
AutoModel model = unmarshal(INPUT_FILE);
JTable table = new JTable(model) {
#Override
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
};
JOptionPane.showMessageDialog(null, new JScrollPane(table));
marshal(model, OUTPUT_FILE);
}
private static void marshal(AutoModel model, String file) throws Exception {
JAXBContext context = JAXBContext.newInstance(AutoModel.class);
Marshaller marshaller = context.createMarshaller();
File f= new File(file);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(model, f);
}
private static AutoModel unmarshal(String file) throws Exception {
JAXBContext context = JAXBContext.newInstance(AutoModel.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
AutoModel model = (AutoModel)unmarshaller.unmarshal(new File(file));
return model;
}
}
As far the the AutoModel goes, it only works for your first table. You will need to create another model for your repairs table. Also, the model, currently only offered read-only. You will need to add other functionality to say add a row and set individual values.
Here are some resources to look at:
How to Use Tables: Creating a Table Model
JAXB Specification toturial
NOTE: With the JAXB annotations above you can create the schema, and you you want to validate the xml against it, you could just set the schema when you unmarshal. Something like:
private static AutoModel unmarshal(String file) throws Exception {
JAXBContext context = JAXBContext.newInstance(AutoModel.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File("src/table/autos.xsd"));
unmarshaller.setSchema(schema);
AutoModel model = (AutoModel)unmarshaller.unmarshal(new File(file));
return model;
}
It may be a basic question, but I could not manage to find a correct answer. Maybe it is an exceptional usage of SimpleXML.
In SimpleXML (java) I want to read some attributes of an object from XML and then save the Object again to another XML without writing those attributes.
I want to read "Question" object from this XML definition:
<question>
<questionID>0</questionID>
<category>tarih</category>
<difficultyLevel>80</difficultyLevel>
<text>Tarihte gelmiş geçmiş en büyük sınırlara ulaşan imparatorluk, aşağıdakilerden hangisidir?</text>
<alternatives length="4">
<string>Britanya</string>
<string>Roma</string>
<string>Moğol</string>
<string>Osmanlı</string>
</alternatives>
<answerID>0</answerID>
And Serialize it back as follows by eliminating the "alternatives" fields:
<question>
<questionID>0</questionID>
<category>tarih</category>
<difficultyLevel>80</difficultyLevel>
<text>Tarihte gelmiş geçmiş en büyük sınırlara ulaşan imparatorluk, aşağıdakilerden hangisidir?</text>
<answerID>0</answerID>
</question>
Is this possible?
Edit: The java class definition of "Question":
public class Question {
public final static int N_POSSIBLE_ANSWERS=4;
public final static String[] ALTERNATIVE_CAPTIONS = {"A","B","C","D"};
// Attributes
#Element
public int questionID;
#Element
public String category;
#Element
public int difficultyLevel;
#Element
public String text;
#ElementArray
private String[] alternatives;
#Element(required=false)
private int answerID = -1;
// State variables
private int nAddedAlternatives=0;
public String[] getAlternatives() {
return alternatives;
}
public void addAlternative(String alternative){
if(alternatives == null){
alternatives = new String[N_POSSIBLE_ANSWERS];
}
alternatives[nAddedAlternatives] = alternative;
nAddedAlternatives++;
}
public void clearAlternatives(){
nAddedAlternatives = 0;
alternatives = null;
}
public String getAlternative(int i){
//String result = ALTERNATIVE_CAPTIONS[i];
//result += ": ";
String result = alternatives[i];
return result;
}
public int getAnswer(){
return answerID;
}
public void setAnswer(int answer){
answerID = answer;
}
}
The ElementArray defined as "alternatives" is the interest point of this question.
Best regards,
fercis
Please use the below method to convert that
public static void convert(InputStream inputStream,OutputStream outputStream,List<String> result) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(inputStream);
if(inputStream != null)
inputStream.close();
NodeList childNodes = document.getChildNodes().item(0).getChildNodes();
Document writeDoc = builder.newDocument();
Element rootElement = writeDoc.createElement(document.getChildNodes().item(0).getNodeName());
for (int i = 0; i < childNodes.getLength(); i++) {
Node item = childNodes.item(i);
if(result.contains(item.getNodeName())) {
System.out.println("Skipped ...");
continue;
}
Node node = item.cloneNode(true);
writeDoc.adoptNode(node);
rootElement.appendChild(node);
}
writeDoc.appendChild(rootElement);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(writeDoc);
transformer.transform(source, new StreamResult(outputStream));
} catch (Exception e) {
e.printStackTrace();
}
}
This is the method which take the input as a InputStream, will return result in OutPutStream, will accept List of String that need to be filtered.
I'm trying to store an ArrayList into an XML file so that I can retrieve the information later on and then display it back into the console.
Can someone show me the most effective way to do this?
EDIT:
Heres what I am trying to write into an external file
// new user is created
Bank bank = new Bank();
System.out.println("Enter your full name below (e.g. John M. Smith): ");
String name = scanner.nextLine();
System.out.println("Create a username: ");
String userName = scanner.nextLine();
System.out.println("Enter your starting deposit amount: ");
int balance = scanner.nextInt();
System.out.print(dash);
System.out.print("Generating your information...\n");
System.out.print(dash);
int pin = bank.PIN();
String accountNum = bank.accountNum();
User user = new User(name, userName, pin, accountNum, balance);
//new user gets added to the array list
Bank.users.add(user);
System.out.println(user);
This all creates a Bank user, which gets thrown into an ArrayList, then I want to store their information so that I can come back later and redisplay it.
public static void main(String[] args) {
// TODO Auto-generated method stub
WriteFile ob = new WriteFile();
ArrayList list = new ArrayList();
list.add(new details("A", 20, 1));
list.add(new details("B", 30, 2));
ob.writeXmlFile(list);
}
// Modify this below class as per your need
class details {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
int age;
int id;
public details() {
}
public details(String name_, int age_, int id_) {
name = name_;
age = age_;
id = id_;
}
// below class actually writed
public void writeXmlFile(ArrayList<details> list) {
try {
DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
DocumentBuilder build = dFact.newDocumentBuilder();
Document doc = build.newDocument();
Element root = doc.createElement("Studentinfo");
doc.appendChild(root);
Element Details = doc.createElement("Details");
root.appendChild(Details);
for (details dtl : list) {
Element name = doc.createElement("Name");
name.appendChild(doc.createTextNode(String.valueOf(dtl
.getName())));
Details.appendChild(name);
Element id = doc.createElement("ID");
id.appendChild(doc.createTextNode(String.valueOf(dtl.getId())));
Details.appendChild(id);
Element mmi = doc.createElement("Age");
mmi.appendChild(doc.createTextNode(String.valueOf(dtl.getAge())));
Details.appendChild(mmi);
}
// Save the document to the disk file
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
// format the XML nicely
aTransformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
aTransformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
try {
// location and name of XML file you can change as per need
FileWriter fos = new FileWriter("./ros.xml");
StreamResult result = new StreamResult(fos);
aTransformer.transform(source, result);
} catch (IOException e) {
e.printStackTrace();
}
} catch (TransformerException ex) {
System.out.println("Error outputting document");
} catch (ParserConfigurationException ex) {
System.out.println("Error building document");
}
}
The way I do it is either using XStream or Jackson API (preferred) to serialize the java object to either a XML or a JSON file.
For example, see my XStream data provider I wrote for use with TestNG or JUnit parameterized tests.
How about using XMLEncoder/XMLDecoder?
http://docs.oracle.com/javase/6/docs/api/java/beans/XMLEncoder.html
Copy and paraphrasing from the javadoc.
ArrayList arr = new ArrayList();
// populate your array
XMLEncoder e = new XMLEncoder(BufferedOutputStream(
new FileOutputStream("Test.xml")));
e.writeObject(arr);
e.close();
Similarly, the reverse to decode.
I use Simple XML (simple-xml-2.6.2.jar) to parse xml file like:
<?xml version="1.0" encoding="UTF-8" ?>
<orderList>
<order id="1">
<name>NAME1</name>
</order>
<order id="2">
<name>NAME2</name>
</order>
</orderList>
The root Element contains subElements.
I wanna it be ArrayList, How to do it?
Here's a possible solution, hope it helps you:
Annotations of Order class:
#Root(name="order")
public class Order
{
#Attribute(name="id", required=true)
private int id;
#Element(name="name", required=true)
private String name;
public Order(int id, String name)
{
this.id = id;
this.name = name;
}
public Order() { }
// Getter / Setter
}
Example class, containing the list:
#Root(name="elementList")
public class Example
{
#ElementList(required=true, inline=true)
private List<Order> list = new ArrayList<>();
// ...
}
And here's some code for reading your code:
Serializer ser = new Persister();
Example example = ser.read(Example.class, file); // file = your xml file
// 'list' now contains all your Orders
List is an interface, ArrayList is one of its implementation, like:
List<Order> l = new ArrayList<Order>()
So if you have a List , you basically have what you want.
If I've interpreted your question correctly, you want a list of orders. I've not tested this for your setup but this works for me for a similar xml structure (assumes you have a custom class called Order):
List<Order> orders = new ArrayList<Order>();
XMLDOMParser parser = new XMLDOMParser();
AssetManager manager = context.getAssets();
InputStream stream;
try {
stream = manager.open("test.xml"); //need full path to your file here - mine is stored in assets folder
Document doc = parser.getDocument(stream);
}catch(IOException ex){
System.out.printf("Error reading xml file %s\n", ex.getMessage());
}
NodeList nodeList = doc.getElementsByTagName("order");
for (int i = 0; i < nodeList.getLength(); i++) {
Element e = (Element) nodeList.item(i); //each order item
Node order=nodeList.item(i);
subList = order.getFirstChild(); //get the name child node
orders.add(order);
}
//XMLDOMParser Class
public class XMLDOMParser {
//Returns the entire XML document
public Document getDocument(InputStream inputStream) {
Document document = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(inputStream);
document = db.parse(inputSource);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return document;
}
/*
* I take a XML element and the tag name, look for the tag and get
* the text content i.e for <employee><name>Kumar</name></employee>
* XML snippet if the Element points to employee node and tagName
* is name I will return Kumar. Calls the private method
* getTextNodeValue(node) which returns the text value, say in our
* example Kumar. */
public String getValue(Element item, String name) {
NodeList nodes = item.getElementsByTagName(name);
return this.getTextNodeValue(nodes.item(0));
}
private final String getTextNodeValue(Node node) {
Node child;
if (node != null) {
if (node.hasChildNodes()) {
child = node.getFirstChild();
while(child != null) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
child = child.getNextSibling();
}
}
}
return "";
}
}