I have 2 xml files .. to e merged in 1 xml file
input files:
reference.xml
<company>
<staff>
<name>
<surname>smith </surname>
</name>
<phone>465456433</phone>
<email>gmail1</email>
</staff>
</company>
comparison.xml
<company>
<staff>
<name>
<initials>js</initials>
</name>
<area>area1</area>
<city>city1</city>
</staff>
</company>
expected output:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
<staff>
<name>
<surname>smith</surname>
<initials>js</initials>
</name>
<phone>465456433</phone>
<email>gmail1</email>
<area>area1</area>
<city>city1</city>
</staff>
</company>
I get that output with a hardcoded code by getting tag names.. But is there a way to loop over each parent node and import its children from the 2 files without naming tags to be GENERIC
public class merge {
public static void main(String[] args) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
Document doc = null;
Document doc2 = null;
try {
///////////////////////////////////////////////////////////////////////
db = dbf.newDocumentBuilder();
doc = db.parse(new File("C:/Users/IBM_ADMIN/Desktop/reference.xml"));
doc2 = db.parse(new File("C:/Users/IBM_ADMIN/Desktop/comparison.xml"));
NodeList ndListFirstFile = doc.getElementsByTagName("staff");
Node nodeArea = doc.importNode(doc2.getElementsByTagName("area").item(0), true);
Node nodeCity = doc.importNode(doc2.getElementsByTagName("city").item(0), true);
ndListFirstFile.item(0).appendChild(nodeArea);
ndListFirstFile.item(0).appendChild(nodeCity);
NodeList ndList = doc.getElementsByTagName("name");
Node nodesur = doc.importNode(doc.getElementsByTagName("surname").item(0), true);
Node nodein = doc.importNode(doc2.getElementsByTagName("initials").item(0), true);
ndList.item(0).appendChild(nodesur);
ndList.item(0).appendChild(nodein);
///////////////////////////////////////////////////////////////////
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);
Writer output = new BufferedWriter(new FileWriter("C:/Users/IBM_ADMIN/Desktop/final.xml"));
String xmlOutput = result.getWriter().toString();
output.write(xmlOutput);
output.close();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks
You can use
NodeList list = doc.getChildNodes();
But then you have to check each child to verify it is an element.
for (int i = 0; i < list.getLength(); ++i)
{
Node n = list.item(i);
if (n.getType().equals(Node.ELEMENT_NODE))
{
n.getNodeName();
}
}
Something like that. To handle all elements in a document you have to use a Breadth/Depth First algorithm.
Stack<Node> pending = new Stack<Node>();
pending.push(doc.getChildNodes().item(0));
while(!pending.empty())
{
Node n = pending.pop();
n.getChildNodes();
...
}
It should be clear how to move on from here. If not I will work out a more working version when I have time.
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;
}
`
Well, going straight to the point. i'm using java DOM to merge two xml documents in one. To do this i first created a new node to put both documents inside, making the docs, child of the created node. The father has two attributes and one of them is the same as one of my xml document.
The attribute is xmlns="http://www.portalfiscal.inf.br/nfe".
I don't know if there is some xml rule but the child attribute got hide and just the father show the attribute "xmlns".
Here is a stretch of the code i got:
<?xml version="1.0" encoding="UTF-8"?>
-<nfeProc versao="3.10" xmlns="http://www.portalfiscal.inf.br/nfe">
-<NFe>
Here is what i want:
<?xml version="1.0" encoding="UTF-8"?>
-<nfeProc xmlns="http://www.portalfiscal.inf.br/nfe" versao="3.10">
-<NFe xmlns="http://www.portalfiscal.inf.br/nfe">
And here is my code:
public void juntarXML () {
File nota = new File("C:\\NotaFiscalEletronica.xml");
File protocolo = new File("C:\\Protocolo.xml");
//File xml = new File("C:\\xml.xml");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
Document docNota = null;
Document docProtocolo = null;
Document docXML = null;
try {
docBuilder = docFactory.newDocumentBuilder();
docNota = docBuilder.parse(nota);
docProtocolo = docBuilder.parse(protocolo);
docXML = docBuilder.newDocument();
docXML.setXmlVersion("1.0");
// Criando nó pai que conterá os dois documentos
Element nfeProc = docXML.createElement("nfeProc");
nfeProc.setAttribute("xmlns", "http://www.portalfiscal.inf.br/nfe");
nfeProc.setAttribute("versao", "3.10");
docXML.appendChild(nfeProc);
// Buscando e importando os nós dos documentos xml
NodeList list = docXML.getElementsByTagName("nfeProc");
Element listNode = (Element)list.item(0);
String chave = "chave";
for (int i=0; i<2; i++) {
NodeList list2;
Element list2Node;
if (i==0) {
list2 = docNota.getElementsByTagName("NFe"); // Nota Fiscal
list2Node = (Element)list2.item(0);
}else {
list2 = docProtocolo.getElementsByTagName("protNFe"); // Protocolo
list2Node = (Element)list2.item(0);
chave = list2Node.getChildNodes().item(0).getChildNodes().item(2).getTextContent(); // Recuperando a chave
}
Node importedNode = docXML.importNode(list2Node, true);
listNode.appendChild(importedNode);
}
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer trans = transFactory.newTransformer();
trans.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(docXML);
StreamResult result = new StreamResult(new StringWriter());
trans.transform(source, result);
Writer output = new BufferedWriter(new FileWriter("C:\\" + chave + ".xml"));
String xmlOutput = result.getWriter().toString();
//System.out.println(xmlOutput);
output.write(xmlOutput);
output.close();
}catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I had try to re-create the attribute of the node "NFe" and there is no results.
I already checked if the attribute is still there and it is. It just disappear when i put it into a xml document.
So, there is a way to show it??
Taking the opportunity, in the case of "nfeProc", can i set something to not order the attributes alphabetically, to stay the order i add them??
Since now i thank you for the attention.
The two XMLs are the same for a DOM. Descendants inherit the namespace definitions until they are redefined.
So the XML serializer should optimize the the XML and keep only the needed namespace definitions. That means ...
<?xml version="1.0" encoding="UTF-8"?>
<nfeProc versao="3.10" xmlns="http://www.portalfiscal.inf.br/nfe">
<NFe>
...
... is the expected XML document. Here is no reason to have an identical namespace definition on a child element.
Additionally, use createElementNS() - the namespace aware variant of createElement(). This should add the xmlns-attributes automatically as needed.
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);
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.
I'm trying to merge two xml files as shown below but i can't able to get the desired output please help me thank you
Java code:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setIgnoringComments(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(new File("file1.xml"));
Document doc1 = builder.parse(new File("file2.xml"));
NodeList nodes = doc.getElementsByTagName("staff");
NodeList nodes1 = doc1.getElementsByTagName("staff");
for(int i=0;i<nodes1.getLength();i=i+1){
Node n= (Node) doc.importNode(nodes1.item(i), true);
nodes.item(i).getParentNode().appendChild(n);
}
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
Writer output = null;
output = new BufferedWriter(new FileWriter("mergedxml.xml"));
String xmlOutput = result.getWriter().toString();
output.write(xmlOutput);
output.close();
System.out.println("merge complete");
File1.xml
<company>
<staff>
<name>john</name>
<phone>465456433</phone>
<email>gmail1</email>
</staff>
</company>
File2.xml
<company>
<staff>
<area>area1</area>
<city>city1</city>
</staff>
</company>
Current output:
<company>
<staff>
<name>john</name>
<phone>465456433</phone>
<email>gmail1</email>
</staff>
<staff>
<area>area1</area>
<city>city1</city>
</staff>
</company>
Expected Output:
<company>
<staff>
<name>john</name>
<phone>465456433</phone>
<email>gmail1</email>
<area>area1</area>
<city>city1</city>
</staff>
</company>
In order to do that on your own. You should do this following :
public static void mergeXML(){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
Document doc = null;
Document doc2 = null;
try {
db = dbf.newDocumentBuilder();
doc = db.parse(new File("D:\\Loic_Workspace\\Test2\\res\\test.xml"));
doc2 = db.parse(new File("D:\\Loic_Workspace\\Test2\\res\\test2.xml"));
NodeList ndListFirstFile = doc.getElementsByTagName("staff");
Node nodeArea = doc.importNode(doc2.getElementsByTagName("area").item(0), true);
Node nodeCity = doc.importNode(doc2.getElementsByTagName("city").item(0), true);
ndListFirstFile.item(0).appendChild(nodeArea);
ndListFirstFile.item(0).appendChild(nodeCity);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);
Writer output = new BufferedWriter(new FileWriter("D:\\Loic_Workspace\\Test2\\res\\testFinal.xml"));
String xmlOutput = result.getWriter().toString();
output.write(xmlOutput);
output.close();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Final output of testFinal.xml :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
<staff>
<name>john</name>
<phone>465456433</phone>
<email>gmail1</email>
<area>area1</area>
<city>city1</city>
</staff>
</company>
As you want it ;-)
Hope it helps,
This solution is for files where you need to iterate and verify something before to merge.
file1.xml:
<?xml version="1.0" encoding="UTF-8"?>
<reactions>
<reaction>
<ID>07402</ID>
<type>irreversible</type>
<substrate>15666</substrate>
<product>07756</product>
</reaction>
<reaction>
<ID>03063</ID>
<type>irreversible</type>
<substrate>00916</substrate>
<product>04712</product>
</reaction>
file2.xml:
<?xml version="1.0" encoding="UTF-8"?><reactions>
<reaction>
<ID>00001</ID>
<reactionName>polyphosphate polyphosphohydrolase</reactionName>
<reactionDescription> Polyphosphate + n H2O <=> (n+1) Oligophosphate</reactionDescription>
</reaction>
<reaction>
<ID>00002</ID>
<reactionName>Reduced ferredoxin:dinitrogen oxidoreductase (ATP-hydrolysing)</reactionName>
<reactionDescription> 16 ATP + 16 H2O + 8 Reduced ferredoxin <=> 8 e- + 16 Orthophosphate + 16 ADP + 8 Oxidized ferredoxin</reactionDescription>
</reaction>
<reaction>
<ID>03063</ID>
<reactionName>cephalosporin-C:2-oxoglutarate aminotransferase</reactionName>
<reactionDescription> Cephalosporin C + 2-Oxoglutarate <=> (7R)-7-(5-Carboxy-5-oxopentanoyl)aminocephalosporinate + D-Glutamate</reactionDescription>
</reaction>
<reaction>
<ID>07402</ID>
<reactionName>(7R)-7-(4-carboxybutanamido)cephalosporanate amidohydrolase</reactionName>
<reactionDescription> (7R)-7-(4-Carboxybutanamido)cephalosporanate + H2O <=> 7-Aminocephalosporanic acid + Glutarate</reactionDescription>
</reaction>
</reactions>
Result.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<reactions>
<reaction>
<ID>07402</ID>
<type>irreversible</type>
<substrate>15666</substrate>
<product>07756</product>
<reactionName>(7R)-7-(4-carboxybutanamido)cephalosporanate amidohydrolase</reactionName>
<reactionDescription> (7R)-7-(4-Carboxybutanamido)cephalosporanate + H2O <=> 7-Aminocephalosporanic acid + Glutarate</reactionDescription>
</reaction>
<reaction>
<ID>03063</ID>
<type>irreversible</type>
<substrate>00916</substrate>
<product>04712</product>
<reactionName>cephalosporin-C:2-oxoglutarate aminotransferase</reactionName>
<reactionDescription> Cephalosporin C + 2-Oxoglutarate <=> (7R)-7-(5-Carboxy-5-oxopentanoyl)aminocephalosporinate + D-Glutamate</reactionDescription>
</reaction>
</reactions>
Java program to do this:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.io.Writer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class MergeXML {
public static void main(String[] args) {
MergeXML m = new MergeXML();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
db = dbf.newDocumentBuilder();
Document secondaryMetabolismXML = db
.parse(new File("/home/bioinfo/workspace/teste/src/file1.xml"));
Document generalMetabolismXML = db
.parse(new File("/home/bioinfo/workspace/teste/src/file2.xml"));
NodeList secondaryReactions = secondaryMetabolismXML.getElementsByTagName("reaction");
NodeList generalReactions = generalMetabolismXML.getElementsByTagName("reaction");
for (int s = 0; s < secondaryReactions.getLength(); s++) {
Node secondaryReaction = secondaryReactions.item(s);
for (int g = 0; g < generalReactions.getLength(); g++) {
Node generalReaction = generalReactions.item(g);
if (getChildrenByNodeName(secondaryReaction, "ID").getTextContent()
.equals(getChildrenByNodeName(generalReaction, "ID").getTextContent())) {
if (getChildrenByNodeName(generalReaction, "reactionName") != null) {
secondaryReaction.appendChild(secondaryMetabolismXML
.importNode(getChildrenByNodeName(generalReaction, "reactionName"), true));
}
if (getChildrenByNodeName(generalReaction, "reactionAlternativeName") != null) {
secondaryReaction.appendChild(secondaryMetabolismXML.importNode(
getChildrenByNodeName(generalReaction, "reactionAlternativeName"), true));
}
if (getChildrenByNodeName(generalReaction, "reactionDescription") != null) {
secondaryReaction.appendChild(secondaryMetabolismXML
.importNode(getChildrenByNodeName(generalReaction, "reactionDescription"), true));
}
}
}
}
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(secondaryMetabolismXML);
StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);
Writer output = new BufferedWriter(
new FileWriter("/home/bioinfo/workspace/teste/src/Result.xml"));
String xmlOutput = result.getWriter().toString();
output.write(xmlOutput);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns a node child when you have a match with a given node name
*
* #param node
* #param nodeName
* #return
*/
public static Node getChildrenByNodeName(Node node, String nodeName) {
for (Node childNode = node.getFirstChild(); childNode != null;) {
Node nextChild = childNode.getNextSibling();
if (childNode.getNodeName().equalsIgnoreCase(nodeName)) {
return childNode;
}
childNode = nextChild;
}
return null;
}
}
Problem is, you want to append child elements to "staff" element but what you actually do is :
nodes.item(i).getParentNode().appendChild(n);
meaning you're looking for the parent node of one of the "staff" nodes of the list, and that node is "company". So you're appending a new "staff" node (the one imported from doc1) to the "company" node of doc
Now, what you want to do is to iterate over "staff" child nodes of doc1 and to append them one by one to the "staff" node of doc.
So you would want to change nodes1 definition as following :
// Retrieving child nodes of first "staff" element of doc1
NodeList nodes1 = doc1.getElementsByTagName("staff").item(0).getChildNodes();
Then change the node you append that to by replacing
nodes.item(i).getParentNode().appendChild(n);
by
nodes.item(0).appendChild(n);
So now you'll be appending all "staff" child nodes (/!\ only for the first "staff" element) of doc1 to the first "staff" element of doc
Note 1 : Dont use the iteration variable (i) you use to run through list A to select an item of another list unless you're aware of what you're doing (for example both lists are of the same length)
Note 2 : That solution will append the nodes of first "staff" element of doc1 to the first "staff" element of doc. You will maybe want to add some iterations here and there.