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();
}
}
Related
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"
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
}
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);
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;
}
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>