I created below class with getter and setter.
import java.util.List;
public class DMNDetails {
private List<String> inputParam;
private List<String> outputParam;
public List<String> getInputParam() {
return inputParam;
}
public void setInputParam(List<String> inputParam) {
this.inputParam = inputParam;
}
public List<String> getOutputParam() {
return outputParam;
}
public void setOutputParam(List<String> outputParam) {
this.outputParam = outputParam;
}
#Override
public String toString() {
return ("Inputname: "+ getInputParam()+
" Outputname: "+ getOutputParam());
}
}
Extracting input and output variables from XML and return using List.
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ExtractingValues {
public DMNDetails Param() {
List<String> inputval = new ArrayList<String>();
DMNDetails dtls = new DMNDetails();
String variables;
// String dataType;
try {
File file = new File("C:/test.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
// System.out.println("Root element: "+ doc.getDocumentElement().getNodeName());
NodeList nodeList = doc.getElementsByTagName("inputExpression");
for (int i = 0; i < nodeList.getLength(); ++i) {
Node node = nodeList.item(i);
// System.out.println("\nNode Name :" + node.getNodeName());
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element tElement = (Element)node;
variables = tElement.getElementsByTagName("text").item(0).getTextContent();
// dataType = tElement.getAttribute("typeRef");
// System.out.println("Variable: "+ variables);
// System.out.println("Type: "+ dataType);
switch(i) {
case 0:
inputval.add(variables);
// System.out.println("Input1: "+dtls1.getInput1());
break;
case 1:
inputval.add(variables);
// System.out.println("Input2: "+dtls2.getInput2());
break;
case 2:
inputval.add(variables);
// System.out.println("Input3: "+dtls3.getInput3());
break;
default:
System.out.println("Error");
}
}
}
}
catch (Exception e) {
System.out.println(e);
}
dtls.setInputParam(inputval);
/*** OutputVariable Section ***/
List<String> outputval = new ArrayList<String>();
String variablesout;
// String dataType;
try {
File file = new File("C:/Jira_task/Sprint_17/Business.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
// System.out.println("Root element: "+ doc.getDocumentElement().getNodeName());
NodeList nodeList2 = doc.getElementsByTagName("output");
for (int i = 0; i < nodeList2.getLength(); ++i) {
Node node2 = nodeList2.item(i);
// System.out.println("\nNode Name :" + node2.getNodeName());
if (node2.getNodeType() == Node.ELEMENT_NODE) {
Element tElement = (Element)node2;
variablesout = tElement.getAttribute("name");
// dataType = tElement.getAttribute("typeRef");
// System.out.println("Variable: "+ variables);
// System.out.println("Type: "+ dataType);
switch(i) {
case 0:
outputval.add(variablesout);
// System.out.println("Output1: "+dtls1.getOutput1());
break;
case 1:
outputval.add(variablesout);
// System.out.println("Output2: "+dtls2.getOutput2());
break;
case 2:
outputval.add(variablesout);
// System.out.println("Output3: "+dtls3.getOutput3());
break;
default:
System.out.println("Error");
}
}
}
}
catch (Exception e) {
System.out.println(e);
}
dtls.setOutputParam(outputval);
return dtls;
}
}
Here we are get data from "TestCase.xlsx" excel and store in data list and return. My expectation are written inside commented block inside.
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelTestCase2 {
public static List<DMNRow> getdata() throws IOException {
List<DMNRow> data = new ArrayList<>();
// Reading file from local directory
FileInputStream file = new FileInputStream("C:\\TestCase.xlsx");
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook XS = new XSSFWorkbook(file);
int numberofsheets = XS.getNumberOfSheets();
for (int i = 0; i < numberofsheets; i++) {
if (XS.getSheetName(i).equalsIgnoreCase("Sheet1")) {
XSSFSheet XSS = XS.getSheetAt(i);
Iterator<Row> r = XSS.iterator();
/* Here input and output variables are hardcode, but cannot able to hardcode value here, because each xml file contain
n number of input and output. So according to n number of variables we need to extract data from excel and store data
in "data". Datatype also change for each variables.
String cr;
long lc;
String arn;
DMNRow DMNRow;
while (r.hasNext()) {
Row row = r.next();
if (row.getRowNum() == 0) {
continue;
}
cr = row.getCell(0).getStringCellValue();
lc = (long) row.getCell(1).getNumericCellValue();
DataFormatter formatter = new DataFormatter();
arn = formatter.formatCellValue(row.getCell(2));
DMNRow = new DMNRow(cr, lc, arn);
data.add(DMNRow);
*/
}
}
}
// Closing file output streams
XS.close();
file.close();
return data;
}
}
After data from excel store and return to another method to compare data with DMN engine and write status in same excel in Result column.
Can anyone please guide how to store data from excel into list to use by another method for compare.
Related
Though I import all packages it can't work. I am new in java.
Exception in thread "main"
java.lang.NoClassDefFoundError:org/apache/commons/collections4/ListValuedMap
at demo.ReadAndPrintXMLFile.main(ReadAndPrintXMLFile.java:101) Caused
by:java.lang.ClassNotFoundException: org.apache.commons.collections4.
package demo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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 ReadAndPrintXMLFile {
private static XSSFWorkbook workbook;
public static void main(String argv[]) {
ArrayList<String> firstNames = new ArrayList<String>();
ArrayList<String> lastNames = new ArrayList<String>();
ArrayList<String> ages = new ArrayList<String>();
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("D:/amit/book.xml"));
// normalize text representation
doc.getDocumentElement().normalize();
System.out.println("Root element of the doc is :\" "+ doc.getDocumentElement().getNodeName() + "\"");
NodeList listOfPersons = doc.getElementsByTagName("person");
int totalPersons = listOfPersons.getLength();
System.out.println("Total no of people : " + totalPersons);
for (int s = 0; s < listOfPersons.getLength(); s++)
{
Node firstPersonNode = listOfPersons.item(s);
if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE)
{
Element firstPersonElement = (Element) firstPersonNode;
NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
Element firstNameElement = (Element) firstNameList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
System.out.println("First Name : "+ ((Node) textFNList.item(0)).getNodeValue().trim());
firstNames.add(((Node) textFNList.item(0)).getNodeValue().trim());
NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
Element lastNameElement = (Element) lastNameList.item(0);
NodeList textLNList = lastNameElement.getChildNodes();
System.out.println("Last Name : "+ ((Node) textLNList.item(0)).getNodeValue().trim());
lastNames.add(((Node) textLNList.item(0)).getNodeValue().trim());
NodeList ageList = firstPersonElement.getElementsByTagName("age");
Element ageElement = (Element) ageList.item(0);
NodeList textAgeList = ageElement.getChildNodes();
System.out.println("Age : "+ ((Node) textAgeList.item(0)).getNodeValue().trim());
ages.add(((Node) textAgeList.item(0)).getNodeValue().trim());
}// end of if clause
}// end of for loop with s var
for(String firstName:firstNames)
{
System.out.println("firstName : "+firstName);
}
for(String lastName:lastNames)
{
System.out.println("lastName : "+lastName);
}
for(String age:ages)
{
System.out.println("age : "+age);
}
}
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();
}
workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sample sheet");
Map<String, Object[]> data = new HashMap<String, Object[]>();
for(int i=0;i<firstNames.size();i++)
{
data.put(i+"",new Object[]{firstNames.get(i),lastNames.get(i),ages.get(i)});
}
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof Date)
cell.setCellValue((Date) obj);
else if (obj instanceof Boolean)
cell.setCellValue((Boolean) obj);
else if (obj instanceof String)
cell.setCellValue((String) obj);
else if (obj instanceof Double)
cell.setCellValue((Double) obj);
}
}
try {
FileOutputStream out = new FileOutputStream(new File("D:/amit/book1.xlsx"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}// end of main
}
You are missing a dependency to org.apache.commons.collections4. This might be because of your other dependencies (which should have the collections4 dependency in theirs, but apparently there is still some sort of error).
You can try to add the JAR to the path, or if you use any build tools (Maven, Gradle, Ivy, etc.) you can add it to the dependencies list. Try and add this dependency: https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.1
Java Programming
I have a class WeatherAgent. The function of this class is to get the current temperature value and other parameters from a URL (XML code) from World weather online.
My main question is; how to get the generated temperature value in class WeatherAgent into antother class (Boiler)? So, Accessing XML value in class WeatherAgent as a new variable in another class (class Boiler).
package assignment_4;
/*
* imports of class WeatherAgent2
*/
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*
*start class WeatherAgent2
*/
public class WeatherAgent {
private Document getDocument() {
Document doc = null;
try {
URL url = new URL(
"http://api.worldweatheronline.com/free/v1/weather.ashx?q=Eindhoven&format=xml&num_of_days=5&key=87xdd77n893f6akfs6x3jk9s");
URLConnection connection = url.openConnection(); // Connecting to
// URL specified
doc = parseXML(connection.getInputStream());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return doc;
}
private Document parseXML(InputStream stream) throws Exception
{
DocumentBuilderFactory objDocumentBuilderFactory = null;
DocumentBuilder objDocumentBuilder = null;
Document doc = null;
try
{
objDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
objDocumentBuilder = objDocumentBuilderFactory.newDocumentBuilder();
doc = objDocumentBuilder.parse(stream);
}
catch (Exception ex)
{
throw ex;
}
return doc;
}
/*
* get the temperature
*/
public double temperature() {
Document doc = getDocument();
Node Temperature;
Double temp = 0.0;
NodeList forecast = doc.getElementsByTagName("temp_C");
for (int i = 0; i < forecast.getLength(); i++) {
Element element = (Element) forecast.item(i);
NodeList list1 = (NodeList) element.getChildNodes();
Temperature = list1.item(0);
temp = Double.parseDouble(Temperature.getNodeValue());
}
return temp;
}
/*
* get cloud cover
*/
public double cloudcover() {
Document doc = getDocument();
Node Cloudcover;
Double cloudcover = 0.0;
NodeList forecast = doc.getElementsByTagName("cloudcover");
for (int i = 0; i < forecast.getLength(); i++) {
Element element = (Element) forecast.item(i);
NodeList list2 = (NodeList) element.getChildNodes();
Cloudcover = list2.item(0);
cloudcover = Double.parseDouble(Cloudcover.getNodeValue());
}
return cloudcover;
}
/*
* print method
*/
public static void main(String[] argvs) {
WeatherAgent wp = new WeatherAgent();
System.out.println("Temperature: " + wp.temperature());
System.out.println("Cloudcover: " + wp.cloudcover());
}
}
I have this methode in class Boiler to get the temperature value from class WeatherAgent into class Boiler.
It is not working and I do know why. Thanks already for your help!
public double getValueFromAgent(){
double agentTemp = send(URL.create("http://api.worldweatheronline.com/free/v1/weather.ashx?q=Eindhoven&format=xml&num_of_days=5&key=87xdd77n893f6akfs6x3jk9s", "temperature" , null, Double.class));
return agentTemp;
}
There are design patterns for how to structure your classes to share information like this. I'd look into the Observer pattern and the Mediator pattern.
Or in main, when you get the temperature from the WeatherAgent, push it into Boiler. With all of these, the idea is to decouple Boiler from knowing anything about WeatherAgent. It helps with reusability, and makes testing them independently a lot easier.
im trying to get all element of an XML file and put it into a ArrayList>> with a recursive method, but i get an error : Exception in thread "main" java.lang.StackOverflowError at java.util.ArrayList.
the error is getting when i make a recursive call : GetAllXml(ListTree);
and i want to get a strcuture like this [[[un]] , [[deux,trois,quatre]] , [[cinq,six,sept],[huit,noeuf],[dix,onze]]]
here is my code:
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class esperant {
/**
* #param args
*/
private static List<Element> getChildren(Node parent)
{
NodeList nl = parent.getChildNodes();
List<Element> children = new ArrayList<Element>(nl.getLength());
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n instanceof Element)
children.add((Element) n);
}
return children;
}
public static void GetAllXml(ArrayList<ArrayList<ArrayList<Element>>> ListTree)
{
ArrayList<ArrayList<Element>> child = new ArrayList<ArrayList<Element>>();
int level = ListTree.size()-1;
for (int i=0;i<ListTree.get(level).size();i++)
{
for (int j=0;j<ListTree.get(level).get(i).size();j++)
{
ArrayList<Element> childOfChild = new ArrayList<Element>();
childOfChild.addAll(getChildren(ListTree.get(level).get(i).get(j)));
child.add(childOfChild);
}
}
ListTree.add(child);
GetAllXml(ListTree);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<ArrayList<ArrayList<Element>>> ListTree = new ArrayList<ArrayList<ArrayList<Element>>>();
ArrayList<ArrayList<Element>> child = new ArrayList<ArrayList<Element>>();
ArrayList<Element> childOfChild = new ArrayList<Element>();
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.parse("test.xml");
Element root = doc.getDocumentElement();
childOfChild.add(root);
child.add(childOfChild);
ListTree.add(child);
GetAllXml(ListTree);
System.out.println(ListTree);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
here is the xml file :
<?xml version="1.0" encoding="iso-8859-1"?>
<un>
<deux> <cinq></cinq> <six></six> <sept></sept> </deux>
<trois> <huit></huit><noeuf></noeuf> </trois>
<quatre><dix></dix><onze></onze> </quatre>
</un>
Change Your GetAllXml(X) like this, it would work. As Every one above said , there is no way out from this method.
final ArrayList<ArrayList<Element>> child = new ArrayList<ArrayList<Element>>();
final int level = ListTree.size() - 1;
for (int i = 0; i < ListTree.get(level).size(); i++)
{
for (int j = 0; j < ListTree.get(level).get(i).size(); j++)
{
final ArrayList<Element> childOfChild = new ArrayList<Element>();
childOfChild.addAll(getChildren(ListTree.get(level).get(i).get(j)));
if (childOfChild.size() > 0)
{
child.add(childOfChild);
}
}
}
if (child.size() > 0)
{
ListTree.add(child);
GetAllXml(ListTree);
}
Every call on GetAllXml(X), whatever else it does, ends up calling GetAllXml(X) passing the same value as its argument. So it's obvious that it will recurse infinitely.
Is it possible to convert a MS Word to XML file using Apache POI ?
If it is, can you point me to any tutorials for doing that?
I'd say you have two options, both powered by Apache POI
One is to use Apache Tika. Tika is a text and metadata extraction toolkit, and is able to extract fairly rich text from Word documents by making appropriate calls to POI. The result is that Tika will give you XHTML style XML for the contents of your word document.
The other option is to use a class that was added fairly recently to POI, which is WordToHtmlConverter. This will turn your word document into HTML for you, and generally will preserve slightly more of the structure and formatting than Tika will.
Depending on the kind of XML you're hoping to get out, one of these should be a good bet for you. I'd suggest you try both against some of your sample files, and see which one is the best fit for your problem domain and needs.
The purpose of HWPF subproject is exactly that: process Word files.
http://poi.apache.org/hwpf/index.html
Then, to convert the data to XML you have to build XML by the ususal ways: StAX, JDOM, XStream...
Apache offers a Quick Guide:
http://poi.apache.org/hwpf/quick-guide.html
and I also have found that:
http://sanjaal.com/java/tag/simple-java-tutorial-to-read-microsoft-document-in-java/
If you want to process docx files, you might want to look at the OpenXML4J subproject:
http://poi.apache.org/oxml4j/index.html
package com.govind.service;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.log4j.Logger;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.model.StyleDescription;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* DOC to XML converter service
*
* #author govind.sharma
*
*/
public class DocToXmlConverter {
static final Logger logger = Logger.getLogger(DocToXmlConverter.class);
DocumentBuilderFactory docFactory = null;
DocumentBuilder docBuilder = null;
Element rootElement = null;
Document docxml = null;
boolean subHeaders = false;
Element UrlElement = null;
/**
* #param path
* #param fileName
*/
public void processDocxToXml(String path, String fileName) {
XWPFDocument xdoc = null;
FileInputStream fis = null;
String fullPath = path + "/" + fileName + ".docx";
try {
// Read file
fis = new FileInputStream(fullPath);
xdoc = new XWPFDocument(OPCPackage.open(fis));
initializeXml();
// get Document Body Paragraph content
List < XWPFParagraph > paragraphList = xdoc.getParagraphs();
for (XWPFParagraph paragraph: paragraphList) {
String styleName = paragraph.getStyle();
String paraText = paragraph.getParagraphText();
String bulletsPoints = paragraph.getNumFmt();
createXmlTags(styleName, paraText, bulletsPoints);
}
// write the content into XML file
generateXml(path, fileName);
logger.info("Doc to Xml Convertion completed.");
} catch (Exception ex) {
logger.error("Exception while generating XML from DOC" + ex.getMessage());
System.exit(0);
}
}
/**
* #param path
* #param fileName
*/
public void processDocToXml(String path, String fileName) {
HWPFDocument doc = null;
String fullPath = path + "/" + fileName + ".doc";
WordExtractor we = null;
try {
POIFSFileSystem fis = new POIFSFileSystem(new FileInputStream(fullPath));
doc = new HWPFDocument(fis);
} catch (Exception e) {
logger.error("Unable to Read File..." + e.getMessage());
System.exit(0);
}
try {
we = new WordExtractor(doc);
Range range = doc.getRange();
initializeXml();
String[] paragraphs = we.getParagraphText();
for (int i = 0; i < paragraphs.length; i++) {
org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
int j = 0;
while (true) {
CharacterRun run = pr.getCharacterRun(j++);
StyleDescription style = doc.getStyleSheet().getStyleDescription(run.getStyleIndex());
String styleName = style.getName();
String paraText = run.text();
String bulletsPoints = null;
createXmlTags(styleName, paraText, bulletsPoints);
if (run.getEndOffset() == pr.getEndOffset()) {
break;
}
}
}
generateXml(path, fileName);
logger.info("Document to Xml Convertion completed.");
} catch (Exception ex) {
logger.error("Exception while generating XML from DOC" + ex.getMessage());
System.exit(0);
}
}
/**
*
*/
private void initializeXml() {
// initialize XML Document
try {
docFactory = DocumentBuilderFactory.newInstance();
docBuilder = docFactory.newDocumentBuilder();
docxml = docBuilder.newDocument();
rootElement = docxml.createElement("ROOT");
docxml.appendChild(rootElement);
} catch (ParserConfigurationException e) {
logger.error("Exception while initializing XML" + e.getMessage());
}
}
/**
* #param styleName
* #param paragraphText
* #param bulletsPoints
*/
private void createXmlTags(String styleName, String paragraphText, String bulletsPoints) {
// create XML Tags
if (styleName != null && paragraphText.length() > 1) {
if (styleName.equalsIgnoreCase("Style4")) {
Element pragElement = docxml.createElement("TITLE");
pragElement.appendChild(docxml.createTextNode(paragraphText.trim()));
rootElement.appendChild(pragElement);
subHeaders = true;
} else if (styleName.equalsIgnoreCase("Default")) {
Element pragElement = docxml.createElement("P");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
} else if (styleName.equalsIgnoreCase("Normal")) {
Element pragElement = docxml.createElement("P");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
} else if (styleName.equalsIgnoreCase("BodyCopy") && bulletsPoints != null) {
Element pragElement = docxml.createElement("LI");
pragElement.appendChild(docxml.createTextNode(paragraphText));
UrlElement.appendChild(pragElement);
subHeaders = false;
} else if (styleName.equalsIgnoreCase("BodyCopy")) {
Element pragElement = docxml.createElement("PS");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
} else if (styleName.equalsIgnoreCase("ListParagraph")) {
Element pragElement = docxml.createElement("LI");
pragElement.appendChild(docxml.createTextNode(paragraphText));
UrlElement.appendChild(pragElement);
subHeaders = false;
} else if (styleName.equalsIgnoreCase("Subheader1")) {
UrlElement = docxml.createElement("UL");
Element pragElement = docxml.createElement("LI");
pragElement.appendChild(docxml.createTextNode(paragraphText));
UrlElement.appendChild(pragElement);
rootElement.appendChild(UrlElement);
subHeaders = false;
} else {
Element pragElement = docxml.createElement("PS");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
}
} else if (paragraphText.trim().length() > 1) {
Element pragElement = docxml.createElement("P");
pragElement.appendChild(docxml.createTextNode(paragraphText));
rootElement.appendChild(pragElement);
subHeaders = true;
}
if (subHeaders) {
Element pragElement = docxml.createElement("NEWLINE");
pragElement.appendChild(docxml.createTextNode(""));
rootElement.appendChild(pragElement);
}
}
/**
* #param path
* #param fileName
*/
private void generateXml(String path, String fileName) {
try {
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
DOMSource source = new DOMSource(docxml);
StreamResult result = new StreamResult(new File(path + "/" + fileName + ".xml"));
transformer.transform(source, result);
} catch (Exception e) {
logger.error("Exception while generating XML" + e.getMessage());
}
}
}
I've been using xml files to save data from my java program. I'm using the java DOM api. I want to add to the document by adding an element and then adding children to that element.
I tried doing it using this code but when i run it it does nothing. Is there another way of doing it that would be simple and work better? is there a way i can get this code working?
File file = new File("C:/users/peter/desktop/newxml.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
Element newB = document.createElement("B");
Element newC = document.createElement("c");
newC.setTextContent("11");
Element newD = document.createElement("d");
newD.setTextContent("21");
Element newE = document.createElement("e");
newE.setTextContent("31");
newB.appendChild(newC);
newB.appendChild(newD);
newB.appendChild(newE);
document.getDocumentElement().appendChild(newB);
This java code works to append new node to the xml file......it is based on DOM
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
public class writexml1 {
public static void main (String args[])
{
File docFile = new File("..\\jquery\\WebContent\\demo\\testing.xml");
Document doc = null;
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(docFile);
}
catch (java.io.IOException e)
{
System.out.println("Can't find the file");
}
catch (Exception e)
{
System.out.print("Problem parsing the file.");
}
Element root = doc.getDocumentElement();
System.out.println("The root element is " + root.getNodeName() + ".\n");
NodeList children = root.getChildNodes();
System.out.print("There are "+children.getLength()+" child elements.\n");
System.out.print("They are: \n");
//Print the file
for (Node child = root.getFirstChild();child != null;child = child.getNextSibling())
{
if (child.getNodeType() == child.TEXT_NODE)
{
System.out.println("Text: "+child.getNodeValue());
}
else if (child.getNodeType() == child.ELEMENT_NODE)
{
System.out.println(child.getNodeName()+" = "+child.getFirstChild().getNodeValue());
}
}
//NodeList deleteElement = root.getElementsByTagName("staff");
//Node deleteNode= deleteElement.item(0);
//root.removeChild(deleteNode);
Element staffElement = doc.createElement("staff");
Node updateText = doc.createTextNode("");
staffElement.appendChild(updateText);
//
Element firstName = doc.createElement("firstname");
String str_firstName="added firstname";
Node firstNameNode = doc.createTextNode(str_firstName);
firstName.appendChild(firstNameNode);
staffElement.appendChild(firstName);
//
Element lastName = doc.createElement("lastname");
String str_lastName="added lastname";
Node lastNameNode = doc.createTextNode(str_lastName);
lastName.appendChild(lastNameNode);
staffElement.appendChild(lastName);
//
Element nickName = doc.createElement("nickname");
String str_nickName="added nickname";
Node nickNameNode = doc.createTextNode(str_nickName);
nickName.appendChild(nickNameNode);
staffElement.appendChild(nickName);
//
Element salary = doc.createElement("salary");
String str_salary="$10,000";
Node salaryNode = doc.createTextNode(str_salary);
salary.appendChild(salaryNode);
staffElement.appendChild(salary);
//
root.appendChild(staffElement);
//Node StaffNode=(Node)updateElement;
try{
String outputURL = "..\\jquery\\WebContent\\demo\\testing.xml";
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new FileOutputStream(outputURL));
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
you should check out the JAXB API. If I understand right, you're xml looks like this:
<B>
<C>11</C>
<D>21</D>
<E>31</E>
</B>
So code would be:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class B {
#XmlElement public String C; // sloppy, probably should be type Integer or something
#XmlElement public String D;
#XmlElement public String E;
}
// then, somewhere else in your code you want to serialize...
B b = new B();
b.C = "11";
b.D = "21";
b.E = "31";
JAXBContext c = JAXBContext.newInstance(B.class);
// where w is a Writer instance
c.createMarshaller().marshal(b, w);