I want to add some nodes into an existing xml file.
The xml file structure looks like:
<?xml version="1.0" encoding="utf-8" standalone="no"?><?xml-stylesheet type="text/xsl" href="new2.xsl"?><patients>
<patient>
<stoixeia_astheni>
<arithmos_eksetasis>1</arithmos_eksetasis>
<imerominia_eksetasis>11/12/2005</imerominia_eksetasis>
<amka>14385</amka>
<surname>aaa</surname>
<name>aaa</name>
<onoma_patros>aaa</onoma_patros>
<imgennisis>15/03/1984</imgennisis>
<diagnosi>aaa</diagnosi>
<famagogi>depon</famagogi>
</stoixeia_astheni>
<stoixeia_epikoinonias>
<dieuthinsi>aaa</dieuthinsi>
<takodikas>11474</takodikas>
<perioxi>aaa</perioxi>
<stathero>2106425246</stathero>
<kinito>-</kinito>
</stoixeia_epikoinonias>
<loipa_stoixeia>
<fylo>aaa</fylo>
<oikkatastasi>aaa</oikkatastasi>
<epaggelma>aaa</epaggelma>
<istoriko>-</istoriko>
<sxolia>-</sxolia>
</loipa_stoixeia>
</patient>
<patient>
<stoixeia_astheni>
<arithmos_eksetasis>2</arithmos_eksetasis>
<imerominia_eksetasis>12/12/2005</imerominia_eksetasis>
<amka>14325</amka>
<surname>aaa</surname>
<name>aaa</name>
<onoma_patros>aaa</onoma_patros>
<imgennisis>15/03/1984</imgennisis>
<diagnosi>aaa</diagnosi>
<famagogi>depon</famagogi>
</stoixeia_astheni>
<stoixeia_epikoinonias>
<dieuthinsi>aaa</dieuthinsi>
<takodikas>11474</takodikas>
<perioxi>aaa</perioxi>
<stathero>2106425246</stathero>
<kinito>-</kinito>
</stoixeia_epikoinonias>
<loipa_stoixeia>
<fylo>aaa</fylo>
<oikkatastasi>aaa</oikkatastasi>
<epaggelma>aaa</epaggelma>
<istoriko>-</istoriko>
<sxolia>-</sxolia>
</loipa_stoixeia>
</patient>
</patients>
I am trying something like:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String[] elem;
elem = new String[20];
elem [1]="arithmos_eksetasis";
elem [2]="imerominia_eksetasis";
elem [3]="amka";
elem [4]="surname";
elem [5]="name";
elem [6]="onoma_patros";
elem [7]="imgennisis";
elem [8]="diagnosi";
elem [9]="famagogi";
elem [10]="dieuthinsi";
elem [11]="takodikas";
elem [12]="perioxi";
elem [13]="stathero";
elem [14]="kinito";
elem [15]="fylo";
elem [16]="oikkatastasi";
elem [17]="epaggelma";
elem [18]="istoriko";
elem [19]="sxolia";
try {
String filepath = "C:\\Users\\Chris\\Desktop\\tsiou\\workspace\\askhsh3\\WebContent\\askisi3.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
//Node staff = doc.getElementsByTagName("staff").item(0);
// append a new node to staff
Document doc2 = docBuilder.newDocument();
Element patient = doc2.createElement("patient");
Element st_as = doc2.createElement("stoixeia_astheni");
for(int i=1;i<=9;i++){
Element tmp= doc2.createElement(elem[i]);
tmp.appendChild(doc2.createTextNode("aaa"));
st_as.appendChild(tmp);
}
Element st_ep = doc2.createElement("stoixeia_epikoinonias");
for(int i=10;i<=15;i++){
Element tmp= doc2.createElement(elem[i]);
tmp.appendChild(doc2.createTextNode("aaa"));
st_ep.appendChild(tmp);
}
Element st_lp = doc2.createElement("loipa_stoixeia");
for(int i=16; i<=19;i++){
Element tmp= doc2.createElement(elem[i]);
tmp.appendChild(doc2.createTextNode("aaa"));
st_lp.appendChild(tmp);
}
patient.appendChild(st_as);
patient.appendChild(st_ep);
patient.appendChild(st_lp);
doc.importNode(patient,true);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
OutputStream out = new FileOutputStream(filepath);
trans.transform(new DOMSource(doc), new StreamResult(out));
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
}
The result is with no luck (the xml doesn't changed).
When i am trying trans.transform(new DOMSource(patient), new StreamResult(out)); i can see the new patient..i also tried doc.adoptNode(patient)
Any advice would be usefull
In place of doc.importNode(patient,true);, Try this:
//Find existing parent node
Node patientsNode = doc.getElementsByTagName("patients").item(0);
//append the new child node
patientsNode.appendChild(patient);
I am using similar code and it works perfectly.
Related
After form submission, the values are to be stored in an XML file. (XML Dom PArser)
Below given the program which I tried to do the same.
public void writeXMLfile(ApplyLieuDto lieuDto) {
String satDte =
Util.convertUtilDateToString(lieuDto.getSatDutyDteUtil());
//String satDteAMPM = lieuDto.getSatDutyDteAmPm();
//String satDutyDte = satDte + satDteAMPM;
String offDte = Util.convertUtilDateToString(lieuDto.getOffDteUtil());
//String offDteAMPM = lieuDto.getOffDteAmPm();
//String offDate = offDte + offDteAMPM;
String modDate =
Util.convertUtilDateToString(lieuDto.getDateUpdateUtil());
String filePath = "file.xml";
try {
DocumentBuilderFactory docFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("lieu");
doc.appendChild(rootElement);
// staff elements
Element staff = doc.createElement("staff");
rootElement.appendChild(staff);
// set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue(lieuDto.getStaffId());
staff.setAttributeNode(attr);
// name elements
Element firstname = doc.createElement("name");
firstname.appendChild(doc.createTextNode(lieuDto.getName()));
staff.appendChild(firstname);
// contact number elements
Element contact = doc.createElement("contactnumber");
contact.appendChild(doc.createTextNode(lieuDto.getContact()));
staff.appendChild(contact);
// email elements
Element email = doc.createElement("email");
email.appendChild(doc.createTextNode(lieuDto.getEmail()));
staff.appendChild(email);
// satdutydate elements
Element satDutyDate = doc.createElement("satDte");
satDutyDate.appendChild(doc.createTextNode(satDte));
staff.appendChild(satDutyDate);
// satdutydateAMPM elements
Element satDutyDateAMPM = doc.createElement("satDteAMPM");
satDutyDateAMPM.appendChild(doc.createTextNode
(lieuDto.getSatDutyDteAmPm()));
staff.appendChild(satDutyDateAMPM);
// offDate elements
Element offDat = doc.createElement("offdate");
offDat.appendChild(doc.createTextNode(offDte));
staff.appendChild(offDat);
// offDateAMPM elements
Element offDatAMPM = doc.createElement("offdateAMPM");
offDatAMPM.appendChild(doc.createTextNode(lieuDto.getOffDteAmPm()));
staff.appendChild(offDatAMPM);
// appOfficer elements
Element appOfficer = doc.createElement("approvingofficer");
appOfficer.appendChild(doc.createTextNode
(lieuDto.getApprovingOfficer()));
staff.appendChild(appOfficer);
// Date elements
Element modifieddate = doc.createElement("modifieddate");
modifieddate.appendChild(doc.createTextNode(modDate));
staff.appendChild(modifieddate);
// status elements
Element status = doc.createElement("status");
status.appendChild(doc.createTextNode(lieuDto.getStatus()));
staff.appendChild(status);
// write the content into xml file
TransformerFactory transformerFactory =
TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new
FileWriter(filePath,true));
// Output to console for testing
StreamResult strmResult = new StreamResult(System.out);
transformer.transform(source, result);
transformer.transform(source, strmResult);
System.out.println("File saved!");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The output I got as something like this below
<company>
<staff id="1">
<firstname>Priya</firstname>
<lastname>Rajan</lastname>
<salary>100000</salary>
</staff>
</company>
<company>
<staff id="2">
<firstname>Peter</firstname>
<lastname>Jas</lastname>
<salary>100000</salary>
</staff>
</company>
But, the expected result is
<company>
<staff id="1">
<firstname>Priya</firstname>
<lastname>Rajan</lastname>
<salary>100000</salary>
</staff>
<staff id="2">
<firstname>Peter</firstname>
<lastname>Jas</lastname>
<salary>100000</salary>
</staff>
</company>
Root element shouldn't be repeat and, the child nodes only needed to be appended.
Please help me on this.
Thanks.
I got the answer. `
public boolean writeXMLfile(ApplyLieuDto lieuDto)
{
boolean isAdded = false;
String filePath = "file.xml";
DocumentBuilderFactory documentBuilderFactory =
DocumentBuilderFactory.newInstance();
try {
DocumentBuilder documentBuilder =
documentBuilderFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(filePath);
NodeList oldList = doc.getElementsByTagName("staff");
int oldListCount = oldList.getLength();
System.out.println("Old List Count Value :: "+oldListCount);
Element root = doc.getDocumentElement();
Element rootElement = doc.getDocumentElement();
Collection<ApplyLieuDto> svr = new ArrayList<ApplyLieuDto>();
svr.add(lieuDto);
for(ApplyLieuDto lieu : svr)
{
Element staff = doc.createElement("staff");
rootElement.appendChild(staff);
// set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue(lieu.getStaffId());
staff.setAttributeNode(attr);
Element firstname = doc.createElement("name");
firstname.appendChild(doc.createTextNode(lieu.getName()));
staff.appendChild(firstname);
// contact number elements
Element contact = doc.createElement("contactnumber");
contact.appendChild(doc.createTextNode(lieu.getContact()));
staff.appendChild(contact);
// email elements
Element email = doc.createElement("email");
email.appendChild(doc.createTextNode(lieu.getEmail()));
staff.appendChild(email);
String satDte = Util.convertUtilDateToString(lieu.getSatDutyDteUtil());
// satdutydate elements
Element satDutyDate = doc.createElement("satDte");
satDutyDate.appendChild(doc.createTextNode(satDte));
staff.appendChild(satDutyDate);
// satdutydateAMPM elements
Element satDutyDateAMPM = doc.createElement("satDteAMPM");
satDutyDateAMPM.appendChild(doc.createTextNode(lieu.getSatDutyDteAmPm()));
staff.appendChild(satDutyDateAMPM);
String offDte = Util.convertUtilDateToString(lieu.getOffDteUtil());
// offDate elements
Element offDat = doc.createElement("offdate");
offDat.appendChild(doc.createTextNode(offDte));
staff.appendChild(offDat);
// offDateAMPM elements
Element offDatAMPM = doc.createElement("offdateAMPM");
offDatAMPM.appendChild(doc.createTextNode(lieu.getOffDteAmPm()));
staff.appendChild(offDatAMPM);
// appOfficer elements
Element appOfficer = doc.createElement("approvingofficer");
appOfficer.appendChild(doc.createTextNode(lieu.getApprovingOfficer()));
staff.appendChild(appOfficer);
String modDate = Util.convertUtilDateToString(lieu.getDateUpdateUtil());
// Date elements
Element modifieddate = doc.createElement("modifieddate");
modifieddate.appendChild(doc.createTextNode(modDate));
staff.appendChild(modifieddate);
// status elements
Element status = doc.createElement("status");
status.appendChild(doc.createTextNode(lieu.getStatus()));
staff.appendChild(status);
root.appendChild(staff);
}
DOMSource source = new DOMSource(doc);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult result = new StreamResult(filePath);
StreamResult strmResult = new StreamResult(System.out);
transformer.transform(source, result);
transformer.transform(source, strmResult);
NodeList newList = doc.getElementsByTagName("staff");
int newListCount = newList.getLength();
System.out.println("New List Count Value :: "+newListCount);
if(newListCount > oldListCount)
{
isAdded = true;
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
return isAdded;
}
`
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();
}
}
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);
Hi!
I've spent some time to parse an XML document with XPath. It seeams to be a simple task but I got in troubles since the begining.
My code is :
public class QueryXML3 {
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
try {
builder = factory.newDocumentBuilder();
//doc = builder.parse("SampleExample.xml");
InputStream is = QueryXML3.class.getClassLoader().getResourceAsStream("SampleXml.xml");
doc = builder.parse(is);
XPathFactory xpathFactory = XPathFactory.newInstance();
// Create XPath object
XPath xpath = xpathFactory.newXPath();
Node parNode = getParameterNode(doc, xpath);
System.out.println("parameter node:" + parNode);
NodeList res = getParameterNodeList(doc, xpath );
System.out.println("List of nodes" + res);
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
public static Node getParameterNode(Document doc, XPath xpath) {
Node res = null;
try {
res = (Node) xpath.evaluate("/definitions/process", doc, XPathConstants.NODE);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return res;
}
public static NodeList getParameterNodeList(Document doc, XPath xpath) {
NodeList nodeList = null;
try {
nodeList = (NodeList) xpath.evaluate("/definitions/process", doc, XPathConstants.NODESET);
for (int i = 0; i > nodeList.getLength(); i++) {
System.out.print(nodeList.item(i).getNodeName() + " ");
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return nodeList;
}
}
As a result i get this:
parameter node:[process: null]
List of nodes com.sun.org.apache.xml.internal.dtm.ref.DTMNodeList#2f17aadf
I just want to output all the nodes of my xml file and theire attributes...
You are really asking how to serialize an Element to a string - use either a Transformer or DOMImplementationLS.
The NodeList type has no toString() contract and the implementation does not override the default Object.toString(). You need to iterate over the nodes and serialize each Element as above.
You could easily parse an XML file in java using a 3rd party package such as JSoup or JDom.
As an example, here is some simple output of an XML files elements using JSoup:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Java code printing all elements and the selected <from>-element:
String xml = "<note>\n"
+ "<to>Tove</to>\n"
+ "<from>Jani</from>\n"
+ "<heading>Reminder</heading>\n"
+ "<body>Don't forget me this weekend!</body>\n"
+ "</note>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
for (Element e : doc.children()) {
System.out.println(e);
}
Element fromElement = doc.select("from").first();
System.out.println("\nThis is the <from>-element content:\n" + fromElement);
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;
}