I have a trouble in finding info about creating a multi level tags in xml file
for example i want next structure
<UserCards>
<UserCard userCardId="171">
<userName>somename</userName>
<userSurname>somesurname</userSurname>
<userAge>24</userAge>
<userAdress>someadress</userAdress>
<userPhone>223334455</userPhone>
<CurrentBooks>
<booName>someBookName</bookName>
</CurrentBooks>
</UserCard>
</UserCards>
I can create simple one level xml but how can I add new one?
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBulder = docFactory.newDocumentBuilder();
//root mainElement
Document doc = docBulder.newDocument();
Element rootElement = doc.createElement("UserCards");
doc.appendChild(rootElement);
//root Book
Element UserCard = doc.createElement("UserCard");
rootElement.appendChild(UserCard);
...
...
//write in a XMLFile
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("Test/UserCards.xml"));
seems to me like you answered it yourself....
You can append elements to any element, not just the root.
You create all Elements by calling doc.createElement("name")
and append to the parent element of your choice:
Elmenet userName = doc.createElement("userName");
Text userNameText = doc.createTextNode("somename");
userName.appendChild(userNameText);
UserCard.appendChild(userName);
Try this
Element rootElement = doc.createElement("UserCards");
doc.appendChild(rootElement);
//root Book
Element UserCard = doc.createElement("UserCard");
UserCard.setAttribute("userCardId" , "171");
Element userSurname = doc.createElement("userSurname");
UserCard.appendChild(userSurname);
Element userAge = doc.createElement("userAge");
UserCard.appendChild(userAge);
Element userAdress = doc.createElement("userAdress");
UserCard.appendChild(userAdress);
Element userPhone = doc.createElement("userPhone");
UserCard.appendChild(userPhone);
Element CurrentBooks = doc.createElement("CurrentBooks");
Element booKName = doc.createElement("booKName");
CurrentBooks.appendChild(booKName);
UserCard.appendChild(CurrentBooks);
rootElement.appendChild(UserCard);
Related
1RW~800~4~22~1~48:2~true
1RW~800~16~39~1~48:2~true
1RW~800~640~330~1~48:2~true
1RW~800~40~124~1~48:2~true
this is my csv file text and i want to read this and put each value in a row separated by ~ into different xml element . I will loop through this and form 4 different xmls
You can use OpenCSV (short tutorial here) to read your CSV file and write it to a XML.
Here is one way this could be done using the mentioned technologies
// create the CSVReader
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '~');
// create the DocumentBuilder which will create our xml documents
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// create the transoformer which will make the xml ready for storing
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// loop through the 4 rows
for (int i = 0; i < 4; i++) {
// read one row from the csv
String [] line = reader.readNext()
// create an xml document
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("data-"+i);
doc.appendChild(rootElement);
// iterate over the entries in the row
for (String s : line) {
Element element = doc.createElement("element");
element.appendChild(doc.createTextNode(s));
rootElement.appendChild(element);
}
// finally save it:
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("file_"+i+".xml"));
transformer.transform(source, result);
System.out.println("File " + i + " saved!");
}
Hello Im new in useing xml and now trying to append new nodes for existing xml file.
This is my code to write a xml
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBulder = docFactory.newDocumentBuilder();
//root mainElement
Document doc = docBulder.newDocument();
Element rootElement = doc.createElement("Books");
doc.appendChild(rootElement);
//root Book
Element Book = doc.createElement("Book");
rootElement.appendChild(Book);
//setting ganre for a book
Attr att = doc.createAttribute("ganre");
att.setValue(ganre);
Book.setAttributeNode(att);
//book id
Element bookId = doc.createElement("bookId");
bookId.appendChild(doc.createTextNode(randomString(4)));
Book.appendChild(bookId);
//bookname element
Element bookname = doc.createElement("bookName");
bookname.appendChild(doc.createTextNode(name));
Book.appendChild(bookname);
//book author
Element bookAuthor = doc.createElement("bookAuthor");
bookAuthor.appendChild(doc.createTextNode(author));
Book.appendChild(bookAuthor);
//book year
Element bookYear = doc.createElement("bookYear");
bookYear.appendChild(doc.createTextNode(String.valueOf(year)));
Book.appendChild(bookYear);
//book available
Element bookAvail = doc.createElement("bookAvailable");
bookAvail.appendChild(doc.createTextNode(String.valueOf(free)));
Book.appendChild(bookAvail);
//write in a XMLFile
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("Test/Books.xml"));
transformer.transform(source, result);
System.out.println("File saved!");
this is how I trying to append new nodes
File fXmlFile = new File("Test/Books.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
Node books = doc.getFirstChild();
Element newBook = doc.createElement("Book");
[here the troubles comes]
what i want to do is rewrite file like this:
<Books>
<Book ganre="fantasy">
<bookId>7111</bookId>
<bookName>Tron</bookName>
<bookAuthor>Brawm</bookAuthor>
<bookYear>15</bookYear>
<bookAvailable>true</bookAvailable>
</Book>
<Book ganre="action">
<bookId>312</bookId>
<bookName>Corn</bookName>
<bookAuthor>Down</bookAuthor>
<bookYear>23</bookYear>
<bookAvailable>false</bookAvailable>
</Book>
</Books>
but every time Im can only rewrite or damage the xml file.
ps Im getting all my bookName's and so on from the input
I can just suggest to use the JDom library. Its very easy to use and implement, always worked for me.
JDOM is, quite simply, a Java representation of an XML document. JDOM provides a way to represent that document for easy and efficient reading, manipulation, and writing. It has a straightforward API, is a lightweight and fast, and is optimized for the Java programmer. It’s an alternative to DOM and SAX, although it integrates well with both DOM and SAX.
There are some good tutorials at mykong.com explaining how to read, modify and create xml-files :
http://www.mkyong.com/java/how-to-modify-xml-file-in-java-jdom/
problem was solved. My solution is:
File fXmlFile = new File("Test/Books.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
// doc.getDocumentElement().normalize();
Element nList = doc.getDocumentElement();
System.out.println("-----------------------");
//root a new book
Element newBook = doc.createElement("Book");
//setting ganre for a book
Attr att = doc.createAttribute("ganre");
att.setValue(ganre);
newBook.setAttributeNode(att);
//book id
Element bookId = doc.createElement("bookId");
bookId.appendChild(doc.createTextNode(randomString(4)));
newBook.appendChild(bookId);
//bookname element
Element bookname = doc.createElement("bookName");
bookname.appendChild(doc.createTextNode(name));
newBook.appendChild(bookname);
//book author
Element bookAuthor = doc.createElement("bookAuthor");
bookAuthor.appendChild(doc.createTextNode(author));
newBook.appendChild(bookAuthor);
//book year
Element bookYear = doc.createElement("bookYear");
bookYear.appendChild(doc.createTextNode(String.valueOf(year)));
newBook.appendChild(bookYear);
//book available
Element bookAvail = doc.createElement("bookAvailable");
bookAvail.appendChild(doc.createTextNode(String.valueOf(free)));
newBook.appendChild(bookAvail);
nList.appendChild(newBook);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new File("Test/Books.xml"));
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
System.out.println("DONE");
This is my demo.jsp page
String filename = "TestNode.xml";
ServletContext app = getServletContext();
String projectPath = app.getRealPath("/");
String result = projectPath + filename;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(new File(result)));
Element rootElement = doc.getDocumentElement();
Element element1 = doc.getDocumentElement();
Element element2 = doc.createElement("hai");
rootElement.appendChild(element2);
Element name = doc.createElement("welcome");
element2.appendChild(name);
element1.appendChild(element2);
DOMSource src = new DOMSource(doc);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
transformer = transformerFactory.newTransformer();
StreamResult rslt = new StreamResult(result);
transformer.transform(src, rslt);
for this i'm getting output as:
<root>
<hai>
<welcome/>
</hai>
</root>
but expected output is:
<root>
<hai>
<welcome>
</welcome>
</hai>
</root>
Where should I change the code to get expected result?
To obtain the output:
<root>
<hai>
<welcome>
</welcome>
</hai>
</root>
Where the <welcome> </welcome> element is actually not empty but contains at least one whitespace character, you need to create a text node and add it as the child of the welcome element:
Element name = doc.createElement("welcome");
Node textNode = doc.createTextNode(" ");
name.appendChild(textNode);
element2.appendChild(name);
I have an XML document which has null values in its Value tag (something similar to below)
<ns2:Attribute Name="Store" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
<ns2:AttributeValue/>
</ns2:Attribute>
Now, I have to write Java code to modify the values as below.
<ns2:Attribute Name="Store" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
<ns2:AttributeValue>ABCDEF</ns2:AttributeValue>
</ns2:Attribute>
I am using DOM parser to parse the XML. I am able to delete the null tag for " but not able to add new values. I am not even sure if we have a direct way to replace or add the values.
Below is the code I am using to remove the child("")
Node aNode = nodeList.item(i);
eElement = (Element) aNode;
eElement.removeChild(eElement.getFirstChild().getNextSibling());
Thanks in advance
Just add data through setTextContent to the element. Sample code is as below:
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, TransformerException {
String xml = "<ns2:Attribute Name=\"Store\" NameFormat=\"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\"><ns2:AttributeValue/></ns2:Attribute>";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new ByteArrayInputStream(xml.getBytes()));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("ns2:AttributeValue");
for (int i=0;i<nList.getLength();i++) {
Element elem = (Element)nList.item(i);
elem.setTextContent("Content"+i);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println(nList.getLength());
}
I am writing some data to an XML file.
Here is the code:
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
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("1");
staff.setAttributeNode(attr);
// shorten way
// staff.setAttribute("id", "1");
// firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);
// lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("mook kim"));
staff.appendChild(lastname);
// nickname elements
Element nickname = doc.createElement("nickname");
nickname.appendChild(doc.createTextNode("mkyong"));
staff.appendChild(nickname);
// salary elements
Element salary = doc.createElement("salary");
salary.appendChild(doc.createTextNode("100000"));
staff.appendChild(salary);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("file.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
This code writes the XML data to the "file.xml". If I already have a "file.xml" file, what is the best way to append the XML data to the file? Will I need to rewrite the whole above code, or is it easy to adapt the code?
Yes - you're dealing with DOM, so you have to have the whole file in memory. Alternative is StAX.
StreamResult result = new StreamResult(new File("file.xml"));
Check this line.
Replace the above line with this.
StreamResult result = new StreamResult(new FileOutputStream("file.xml", true));
By default the second parameter is false.
True means it will append to file, false means it will overwrite it.