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.
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 want to create new Xml file from the select nodes only i am using dom4j to parse and create new xml file. Example lets assume Nodes Customer name = Joseph is the child of root element TRX i want to show the whole elements that contain joseph and create a new file
enter code here
File inputFile = new File("C:\\Users\\db2admin\\Desktop\\S4decs\\tlog01_004.xml");
SAXReader reader = new SAXReader(true);
reader.setValidation(false);
reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
Document document = reader.read(inputFile);
document.getRootElement();
document.selectNodes("//TRX[#type]='16'").size();
document.selectNodes("/CUSTOMER").size();
// Pretty print the document to System.out
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer;
writer = new XMLWriter( System.out, format );
writer.write( document );
} catch (DocumentException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE TRANSACTIONS SYSTEM "tlog.dtd">
<TRANSACTIONS storeid="4" sbs="780030" location="1">
<TRX type="16" term="742" trxnum="143895" saleperson="0" supervisor_id="152332149" storeid="4" sbs="780030" opcode="153135959" date="20160915" endtime="111000">
</TRX>
<TRX type="31" term="742" trxnum="143896" starttime="095720" supervisor_id="152332149" storeid="4" sbs="780030" opcode="153135959" date="20160915" endtime="111001">
<CASHOPER managerid="153135959">
<PAYMENT id="1" amount="3000.00" descr="CASH" tndnumb="1" exchangetndid="0">
</PAYMENT>
</CASHOPER>
<LINKTRX linktype="8" prevstoreid="4" prevxactdate="2016-09-14" prevxacttime="22:58:29" prevtermid="0" prevxactid="7620" prevoperid="0"></LINKTRX>
</TRX>
<TRX type="16" term="743" trxnum="65729" saleperson="0" supervisor_id="153136068" storeid="4" sbs="780030" opcode="152332262" date="20160915" endtime="111219">
</TRX>
You should select the nodes you need, then append them as children of another element and put this element as root of a new document. Note that first XPath expression seems incorrect (maybe it should be //TRX[#type=16])
private Document daMethod(Document document, String xpath) throws Exception{
List<Node> nodes = document.selectNodes(xpath);
Element newRoot = DocumentHelper.createElement("TRXS");
for (Node node : nodes) {
newRoot.add((Node)node.clone());
}
return DocumentHelper.createDocument(newRoot);
}
Hope it helps.
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.
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 was trying to parse following strings to form a xml document and then trying to extract all child nodes of and add to a different document object which is already available to me.
<dhruba><test>this</test>that<test2>wang chu</test2> something.... </dhruba>
<dhruba>this is text node <test>this</test>that<test2>wang chu</test2> anything..</dhruba>
while I am trying to read the child nodes, it is returning null child for TEXT_NODE for 1st string and null for ELEMENT_NODE for 2nd String, this is wrong, is it API problem ??
I am using following code ... it compile , I am using java 6.
Node n = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
dom = db.newDocument();
Element rootEle = dom.createElement("resources");
// adding the root element to the document
dom.appendChild(rootEle);
Element element = dom.createElement("string");
element.setAttribute("name", "some_name");
try {
n = db.parse(new InputSource(new StringReader("<dhruba><test>this</test>that<test2>node value</test2> some text</dhruba>"))).getDocumentElement();
n = dom.importNode(n, true);
NodeList nodeList = n.getChildNodes();
int length = nodeList.getLength();
System.out.println("Total no of childs : "+length);
for(int count = 0 ; count < length ; count++ ){
Node node = nodeList.item(count);
if(node != null ){
element.appendChild(node);
}
}
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rootEle.appendChild(element);
INPUT :: as string
<dhruba><string name="some_name">
that
<test>this</test>
<test2>node value</test2>
some text
</string>
</dhruba>
EXPECTED OUTPUT :: as document
<string>
<string name="some_name">
<test>this</test>
<test2>node value</test2>
</string>
</string>
if I try to parse
<test>this</test>that<test2>wang chu</test2> something....
then output comes as "thiswang chu"
Why is this happening? what needs to be done if I want to add following node under another document element, i.e. <string>.
<test>this</test>
that
<test2>node value</test2>
some text
[notice that it does not have <dhruba>] inside parent node of another
document.
Hope I am clear. Above code compiles in Java 6
I will assume that this is Java.
First, I'm surprised that you don't get an exception with your importNode() call, since you're importing the Document, which shouldn't be allowed (per the JavaDoc).
Now to the question that you asked: if you only want to attach specific node types, you need to make a test using the node's type. A switch statement is the easiest (note: this has not been compiled, may contain syntax errors):
switch (n.getNodeType())
{
case ELEMENT_NODE :
// append the node to the other tree
break;
default :
// do nothing
}
Probably you want Node.cloneNode() method:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.newDocument();
Element element = dom.createElement("string");
element.setAttribute("name", "some_name");
String inputXMLString =
"<dhruba><test>this</test>that<test2>node value</test2> some text</dhruba>";
Node n = db.parse(new InputSource(new StringReader(inputXMLString))).getDocumentElement();
n = dom.importNode(n, true);
NodeList nodeList = n.getChildNodes();
for (int i = 0; i < nodeList.getLength(); ++i)
{
Node node = nodeList.item(i);
element.appendChild(node.cloneNode(true));
}
dom.appendChild(element);
To get dom into stdout or file you could write:
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
DOMSource source = new DOMSource(dom);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
Result:
<string name="some_name">
<test>this</test>that<test2>node value</test2> some text</string>