Write xml using Java for Multiple Records - java

How to write xml for Multiple records ?
Desired output
<Root>
<Header>
<HeaderTag>Table of Contents</HeaderTag>
<HeaderRow>
<Content>1.Intoduction</Content>
</HeaderRow>
<HeaderRow>
<Content>2.Basics</Content>
</HeaderRow>
</Header>
</Root>
Need looping or iterator for Header Row to accomodate rows for content as mentioned above.
Appreciate your help.
Using below piece of code
public void createRuleXML() {
try {
String newXmlPath = "C:\\write\\CreatedRuleXml.xml";
DocumentBuilderFactory documentFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder =
documentFactory.newDocumentBuilder();
// define root elements
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("Root");
document.appendChild(rootElement);
// define school elements
Element TocHeader = document.createElement("Header");
rootElement.appendChild(TocHeader);
Element HeaderTag = document.createElement("HeaderTag");
HeaderTag.appendChild(document.createTextNode("Table Of Contents"));
TocHeader.appendChild(HeaderTag);
Element TocHeaderRow = document.createElement("HeaderRow");
TocHeader.appendChild(TocHeaderRow);
Element Content = document.createElement("Content");
Content.appendChild(document.createTextNode("1.Introduction"));
TocHeaderRow.appendChild(Content);
Content.appendChild(document.createTextNode("2.Basics"));
TocHeaderRow.appendChild(Content);
However its is returning
Table Of Contents1.Introduction2.Basics

Got fix with below piece of code.
public void createRuleXML() {
try {
String newXmlPath = "C:\\docwrite\\CreatedRuleXml.xml";
DocumentBuilderFactory documentFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentFactory
.newDocumentBuilder();
// define root elements
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("Root");
document.appendChild(rootElement);
// define school elements
Element TocHeader = document.createElement("Header");
rootElement.appendChild(TocHeader);
Element HeaderTag = document.createElement("HeaderTag");
HeaderTag.appendChild(document.createTextNode("Table Of Contents"));
TocHeader.appendChild(HeaderTag);
TocHeader.appendChild(getToc(document, "1.Introduction"));
TocHeader.appendChild(getToc(document, "2.Basics"));
// creating and writing to xml file
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File(newXmlPath));
transformer.transform(domSource, streamResult);
System.out.println("File saved to specified path!");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
private static Node getToc(Document doc, String tocContent) {
Element tocHeaderRow = doc.createElement("HeaderRow");
//create name element
tocHeaderRow.appendChild(getDetailElements(doc, tocHeaderRow, "Content", tocContent));
return tocHeaderRow;
}
//utility method to create text node
private static Node getDetailElements(Document doc, Element element, String name, String value) {
Element node = doc.createElement(name);
node.appendChild(doc.createTextNode(value));
return node;
}

Related

I want append data at the end of text file .xml . I use textfield to SetTextContent . Now I want add next tag on file xml

private void bt_create_xml(ActionEvent e) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("University");
doc.appendChild(rootElement);
Element staff = doc.createElement("student");
// add staff to root
rootElement.appendChild(staff);
// add xml attribute
staff.setAttribute("rollno", tf_input_id.getText());
Element name = doc.createElement("fullname");
name.setTextContent(tf_input_fullname.getText());
staff.appendChild(name);
Element code = doc.createElement("code");
code.setTextContent(tf_input_code.getText());
staff.appendChild(code);
Element birthday = doc.createElement("birthday");
birthday.setTextContent(tf_input_birth.getText());
staff.appendChild(birthday);
Element department = doc.createElement("department");
department.setTextContent(tf_input_depart.getText());
staff.appendChild(department);
Element address = doc.createElement("address");
address.setTextContent(tf_input_add.getText());
staff.appendChild(address);
try{
writeXml(doc, System.out);
FileOutputStream out=new FileOutputStream("D:\\JAVA\\XML-CUOIKY\\XML.xml");
writeXml(doc,out);
}catch (Exception exx){
exx.printStackTrace();
}
} catch (ParserConfigurationException ex) {
ex.printStackTrace();
}
}
private static void writeXml(Document doc,
OutputStream output)
throws TransformerException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// pretty print
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(output);
transformer.transform(source, result);
}
"I want append data at the end of text file .xml . I use textfield to SetTextContent . Now I want add next tag on file xml"

how to add new node under a specific node in dom4j JAVA

I want to generate flexiField tags and add it to current xml file.
Here is My xmlFile.
<com.model.FlexiFieldList>
<flexiFields>
<flexiField>
<fieldDesc>BL</fieldDesc>
<fieldName>BL</fieldName>
<fieldType>FREE_TEXT</fieldType>
<fieldTypeDataStr/>
<sensitive>false</sensitive>
<value>True</value>
<valueType>String</valueType>
</flexiField>
</flexiFields>
</com.model.FlexiFieldList>
I want to add new flexiField and I have this Java Code but When I run my code, it adds flexiField node under <com.model.FlexiFieldList> element
I know that in Element root = document.getDocumentElement(); part we show that we will add new node to root location but I couldnt find any way to change it
Actually My question is that how can I change root path so when I run root.appendChild(newFlexiField); it will add new flexiField node under flexiFields node
File file = new File("C:/Users/xxx/Desktop/ff.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
Element root = document.getDocumentElement();
Collection<FlexiField> flexiFields = new ArrayList<FlexiField>();
flexiFields.add(new FlexiField());
for (FlexiField flexiField : flexiFields) {
// server elements
Element newFlexiField = document.createElement("flexiField");
Element name = document.createElement("fieldDesc");
name.appendChild(document.createTextNode(flexiField.fieldDesc()));
newFlexiField.appendChild(name);
Element port = document.createElement("fieldName");
port.appendChild(document.createTextNode(flexiField.fieldName()));
newFlexiField.appendChild(port);
root.appendChild(newFlexiField);
}
DOMSource source = new DOMSource(document);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
Assumming you have only one <flexiFields> element in you xml file you can try this:
File file = new File("C:/Users/xxx/Desktop/ff.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
Element root = document.getDocumentElement();
// to print your root element
System.out.println("\n*************root************");
System.out.println(root.getNodeName());
// to find the flexiFields
Node firstChild=root.getFirstChild();
while (firstChild != null && firstChild.getNodeType() != Node.ELEMENT_NODE)
{
firstChild = firstChild.getNextSibling();
}
System.out.println(firstChild.getNodeName());
Collection<FlexiField> flexiFields = new ArrayList<FlexiField>();
flexiFields.add(new FlexiField());
for (FlexiField flexiField : flexiFields) {
// server elements
Element newFlexiField = document.createElement("flexiField");
Element name = document.createElement("fieldDesc");
name.appendChild(document.createTextNode(flexiField.fieldDesc()));
newFlexiField.appendChild(name);
Element port = document.createElement("fieldName");
port.appendChild(document.createTextNode(flexiField.fieldName()));
// append your child
newFlexiField.appendChild(port);
firstChild.appendChild(newFlexiField);
}
DOMSource source = new DOMSource(document);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult result = new StreamResult(file);
transformer.transform(source, result);

How to add sibling and child nodes into a XML file?

The purpose of my program is to add a group of words that are in an array within a loop. Assume in each iteration it should add words from a starting index to an ending index to a node as its children. The XML file and each node should be made in a run-time basis, but there is a consideration that if the program is stopped and then run the program again, it should continue adding new words into the existing XML file by adding a new node after the last existing node. Here is how I get to make the XML file and add nodes to it, but it adds nodes to the root node and they are without any child (the child should be added into each node within an iteration but they are considered as a separate node and not a child node):
private static void createXML(String word, int id) {
Element Word= doc.createElement("word"+id);
rootElement.appendChild(Word);
//doc.appendChild(Word);
Attr attr = doc.createAttribute("id");
attr.setValue(Integer.toString(id));
Word.setAttributeNode(attr);
Element Content= doc.createElement("content");
Content.appendChild(doc.createTextNode(word));
Word.appendChild(Content);
}
private static void saveXML() {
transformerFactory = TransformerFactory.newInstance();
transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("g:\\words.xml"));
transformer.transform(source, result);
}
public static void main(String[] args){
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Element doc = docBuilder.newDocument();
Element rootElement = doc.createElement("WORDS");
doc.appendChild(rootElement);
for(int i=m, i<n; i++)
createXML(array[m...n], i);
saveXML();
}
In case anyone wonder how to do it, here is the change that need to make:
private static void createXMLnew(String[] words) {
Element[] word=new Element[words.size()];
for(int i=0;i<words.size();i++){
if(i==0)
{
word[0] = doc.createElement("word"+0);
rootElement.appendChild(url[0]);
Attr attr = doc.createAttribute("id");
attr.setValue(Integer.toString(0));
word[0].setAttributeNode(attr);
Element adr = doc.createElement("adr");
adr.appendChild(doc.createTextNode(words[0]));
words[0].appendChild(adr);
}
else{
word[i] = doc.createElement("word"+i);
word[0].appendChild(word[i]);
Attr attr = doc.createAttribute("id");
attr.setValue(Integer.toString(i));
word[i].setAttributeNode(attr);
Element adr = doc.createElement("adr");
adr.appendChild(doc.createTextNode(words[i]));
words[i].appendChild(adr);
}
}
}
In this case, the first element will be the father of the rest. To make each XML file to contain unique items, need to make this change to the save()
private static void saveXML(int i) {
transformerFactory = TransformerFactory.newInstance();
transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("g:\\words"+i+".xml"));
transformer.transform(source, result);
docFactory = DocumentBuilderFactory.newInstance();
docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.newDocument();
rootElement = doc.createElement("WORDS");
doc.appendChild(rootElement);
//all these added objects need to be defined as static object out of main() function
}

Java read XML and put textnodes into an array of strings?

I apologize if this question has been asked somewhere, I've been searching on google for over an hour and can't seem to figure out how to do this.
I've created a config file for an application I'm making which is stored in XML and I've gotten the application to successfully create the XML file if it doesn't exist using DOM,
(code,in case it's needed)
public static void newConfig() {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root element
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("settings");
doc.appendChild(rootElement);
// address element
Element address = doc.createElement("address");
address.appendChild(doc.createTextNode("127.0.0.1"));
rootElement.appendChild(address);
// port element
Element port = doc.createElement("port");
port.appendChild(doc.createTextNode("3306"));
rootElement.appendChild(port);
// user element
Element user = doc.createElement("user");
user.appendChild(doc.createTextNode("user"));
rootElement.appendChild(address);
// password element
Element pass = doc.createElement("pass");
pass.appendChild(doc.createTextNode("password"));
rootElement.appendChild(pass);
// database element
Element datab = doc.createElement("database");
datab.appendChild(doc.createTextNode("A1"));
rootElement.appendChild(datab);
// write the content to XML
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("config.xml"));
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
which creates this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<settings>
<port>3306</port>
<address>127.0.0.1</address>
<pass>password</pass>
<database>A1</database>
</settings>
how would I go about retrieving those textnodes as an array of strings?
try this
NodeList nodes = docBuilder.parse(new File("1.xml")).getDocumentElement().getChildNodes();
String[] a = new String[4];
for (int i = 0, j = 0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
if (n instanceof Element) {
a[j++] = n.getTextContent().trim();
}
}

How I can insert node at beginning xml file?

I need insert node to the beginning of my XML file, after I sought in web I found keyword insertBefore but I can't apply this keyword in my code. However when I used appendChild, then inserted this keyword the element gets inserted to the end of xml file.How can I use insertBefore keyword to insert to beginning of xml tree.
For example:
<n>
<a2>
<b></b> <c></c>
</a2>
<a1>
<b></b> <c></c>
</a1>
</n>
I need to insert element to the beginning of the xml file same that:
<n>
<a1>
<b></b> <c></c>
</a1>
<a2>
<b></b> <c></c>
</a2>
</n>
my java code:
public void insertNewProject(Project entity) {
String filePath = "location.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc;
doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
Node n = doc.getElementsByTagName("n").item(0);
Element a = doc.createElement("a");
n.appendChild(a);
Element b = doc.createElement("b");
b.appendChild(doc.createTextNode(entity.getLocation()));
a.appendChild(b);
Element c = doc.createElement("c");
c.appendChild(doc.createTextNode(entity.getName()));
a.appendChild(c);
doc.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(doc);
StreamResult streamResult = new StreamResult(new File("location.xml"));
transformer.transform(domSource, streamResult);
} catch (ParserConfigurationException pce) {
return;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException tfe) {
return;
}
}
Why cant you use the firstChild method and then insert before? Like
n.insertBefore(a, n.getFirstChild());
Full code
public void insertNewProject(Project entity) {
String filePath = "location.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc;
doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
Node n = doc.getElementsByTagName("n").item(0);
Element a = doc.createElement("a");
n.insertBefore(a, n.getFirstChild());
Element b = doc.createElement("b");
b.appendChild(doc.createTextNode(entity.getLocation()));
a.appendChild(b);
Element c = doc.createElement("c");
c.appendChild(doc.createTextNode(entity.getName()));
a.appendChild(c);
doc.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(doc);
StreamResult streamResult = new StreamResult(new File("location.xml"));
transformer.transform(domSource, streamResult);
} catch (ParserConfigurationException pce) {
return;
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TransformerException tfe) {
return;
}
}
I changed the following part in your code.
Please check if this is what you are looking for?
Node n = doc.getElementsByTagName("n").item(0);
Element a = doc.createElement("a");
Node a2 = doc.getElementsByTagName("a2").item(0);
n.insertBefore(a, a2);//.appendChild(a);
to insert an element in start you need to know what is first element. then you can insert node in start by following changes in your code
doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
NodeList nlist = doc.getElementsByTagName("a2");
Node n = doc.getElementsByTagName("n").item(0);
Node a1 = nlist.item(0);
Element a = doc.createElement("a");
n.insertBefore(a, a1);

Categories