XML file saved from Swing application - java

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

Related

How to print xml file colored in console using java

I'm trying to print an XML file colored on console using java, but I have never done this before, and I have no idea how to do that.
This code prints an XML file on console.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder1;
builder1 = factory.newDocumentBuilder();
Document document;
document = builder1.parse(new File(pathFilename));
TransformerFactory tFactory = TransformerFactory.newInstance();
tFactory.setAttribute("indent-number", new Integer(2));
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(document);
StreamResult result2 = new StreamResult(System.out);
transformer.transform(source, result2);
I would like to print it on console like an editor, for example Notepad++.
Any suggests how to do it?
An example of output on console:
<ControllerMode dataItemId="mode" sequence="286201" timestamp="2019-06-27T11:23:02.641182Z">AUTOMATIC</ControllerMode>

DOM Parser not able to parse large xml file

I am trying to parse a large xml file using DOM Parser and Xpath, but it seems like my code breaks as it's a large xml file (60000 lines). When I try and print the xml, it starts printing from the middle of the xml. Any ideas how I can avoid this?
Regards
FileInputStream file = new FileInputStream(new File(filePath));
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
disclaimer = xPath.compile(disclaimerPath + File.separator + "title").evaluate(xmlDocument);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer));
System.out.println(writer.getBuffer().toString().replaceAll("\n|\r", ""));

How to create line breaks in xml using java

I want to create an xml file with line breaks, looking somewhat like this:
<Instrument currencyId="THB"
disabledCount="0"
hasBeenEnabledOnce="TRUE"
</Instrument>
Using this code I got close but all attributes seems to be end up on the same row:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Instrument");
doc.appendChild(rootElement);
Instrument.setAttribute("currencyId", "THB");
Instrument.setAttribute("disabledCount", "0");
Instrument.setAttribute("hasBeenEnabledOnce", "TRUE");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\file.xml"));
transformer.transform(source, result);
I get the following result:
<Instrument currencyId="THB" disabledCount="0" hasBeenEnabledOnce="TRUE"
How can I add linebreaks between the attributes??
just a slight notice, I thought that transformer.setOutputProperies could solve the problem, by searching for similar problems I ended up with "OutputKeys.INDENT", "yes", and the indent-amount -> "4". But nothing's changed.
Doesnt matter if I open the file in notepad++ or as a webpage.

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

How to set UTF-16 encoding format for Xml?

I am in need to create xml as a string to pass to server. I have managed to convert the data into xml but the encoding format set to utf-8 as default. What i need is i want to set it as utf-16 format. But i haven't got any idea of setting it.
private void XmlCreation(int size,List<DataItem> item) throws ParserConfigurationException, TransformerException
{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("ArrayOfDataItem");
document.appendChild(rootElement);
for (DataItem in: item)
{
Element subroot = document.createElement("DataItem");
rootElement.appendChild(subroot);
Element em = document.createElement(in.getKey());
em.appendChild(document.createTextNode(in.getValue()));
subroot.appendChild(em);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
java.io.StringWriter sw = new java.io.StringWriter();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
String xml = sw.toString();
System.out.println(xml);
}
}
Thanks guys
I haven't tested, but that should do the trick:
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-16");
This article might help you. Basically, you call setOutputProperty with OutputKeys.ENCODING as key and the desired encoding ("UTF-16") as value.

Categories

Resources