How to append new nodes to an existing xml file - java

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");

Related

How to create multi level xml file

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);

Renaming the root node of XML in Java

I would like to rename my root node of an XML in Java.
I tried various solutions but none did work.
My code:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File xmlFile = new File("C:/test.xml");
Document doc = builder.parse(new FileInputStream(xmlFile));
File xmiFile = new File("C:/test.xmi");
FileMover.copyFile(xmlFile, xmiFile);
Document doc2 = builder.parse(new FileInputStream(xmiFile));
doc2.importNode(doc.getDocumentElement(), true);
doc2.getElementsByTagName("report");
Node reportNode = doc2.getDocumentElement();
Element reportElement = (Element) reportNode;
doc2.renameNode(reportElement, "reports.dtd", "report:ReportType");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Source source2 = new DOMSource(doc2.getDocumentElement());
StringWriter out = new StringWriter();
Result result2 = new StreamResult(out);
transformer.transform(source2, result2);
Running the code, I get this exception:
Exception in thread "Main Thread" org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.insertBefore(CoreDocumentImpl.java:392)
at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.renameNode(CoreDocumentImpl.java:1047)
at XMIConverter.main(XMIConverter.java:57)

Modifying an XML in Java

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

XML file saved from Swing application

I'm developing a Java Swing Application, and I want to create objects and save them in a XML file, with the information that a user writes in some text fields.
How can I save that data into a XML file, to form those objects?
You can write your own XML-Writer to write out objects/text to a XML file. For example using DOM
public boolean writeCommonSettingsFromGUI()
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("NAME_OF_A_ELEMENT");
doc.appendChild(rootElement);
Element xmlInfo = doc.createElement("NAME_OF_ANOTHER_ELEMENT");
xmlInfo.setTextContent("YOUR_CONTENT_TO_SET_FOR_THIS_ELEMENT");
rootElement.appendChild(xmlInfo);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "5");
transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
DOMSource source = new DOMSource(doc);
StreamResult result = null;
result = new StreamResult(new File("FILE_PATH_WHERE_TO_SAVE_YOUR_XML"));
transformer.transform(source, result);
return true;
}
use castor framework, you can map your java class to xml file and vice versa

Editing xml content in java and passing it as string, using node preferably

I've a xml document, which will be used as a template
<?xml version="1.0" encoding="UTF-8" standalone="no"?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><content type="application/xml"><m:properties><d:AccountEnabled>true</d:AccountEnabled><d:DisplayName>SampleAppTestj5</d:DisplayName><d:MailNickname>saTestj5</d:MailNickname><d:Password>Qwerty1234</d:Password><d:UserPrincipalName>saTestj5#identropy.us</d:UserPrincipalName></m:properties></content></entry>
I'm calling it in java using this code where payLoadXML.xml has the above content.
"InputStream is = getClass().getClassLoader().getResourceAsStream("/payLoadXML.xml");"
Now I'm trying to edit the tag values for example changing the from "saTestj5" to "saTestj6" and then converting this entire xml and storing it in xml. Can anyone tell me how can I achieve this? I was told this can be done by using "Node" is it possible?
Use jaxb or sax parsers convert into object by using getter method and change the object and convert back to xml
try this
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
docBuilder = docFactory.newDocumentBuilder();
Document doc = null;
InputStream is = getClass().getClassLoader().getResourceAsStream("/payLoadXML.xml");
doc = docBuilder.parse(is);
Node staff = doc.getElementsByTagName("m:properties").item(0);
Text givenNameValue = doc.createTextNode("abc");
Element givenName = doc.createElement("d:GivenName");
givenName.appendChild(givenNameValue);
staff.appendChild(givenName);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);

Categories

Resources