Preserve newline in xml while using builder.parse method & Transformer - java

The objective is to read from a xml file and write to a new xml file while preserving newlines. We need the Document object to perform other xml tasks.
Say source.xml looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Code><![CDATA[code line1
code line 2
code line 3
code line 4]]></Code>
Now the destination should look the same with the newlines in the code element. But instead it ignores the newlines and makes it one line.
For writing, I am using the method below:
public static void writeFile(Document xml, File writeTo)
{
try
{
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
DOMSource source = new DOMSource(xml);
StreamResult result = new StreamResult(writeTo);
transformer.transform(source, result);
}
catch(TransformerException e)
{
System.out.println("Couldn't write file " + writeTo);
e.printStackTrace();
}
}
The Document xml is obtained using Parse(File) method in DocumentBuilder. Roughly in the lines of:
File file; // a list of files is recursively obtained from a given folder.
DocumentBuilderFactory documentBuilderfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderfactory.newDocumentBuilder();
Document xml = builder.parse(file);
The builder.parse seems to be losing the newlines in the CDATA of Code element.
How do we preserve the newlines?
I am new to Java APIs.

When I put your snippets together I get this program:
public class TestNewLine {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, TransformerException {
DocumentBuilderFactory documentBuilderfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderfactory.newDocumentBuilder();
Document xml = builder.parse(TestNewLine.class.getResourceAsStream("data.xml"));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
DOMSource source = new DOMSource(xml);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
}
}
and it prints out:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Code><![CDATA[code line1
code line 2
code line 3
code line 4]]></Code>
As far as I understood, the newline is preserved already. What output did you expect?

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>

how to update XML data from java

I want to change the text content of some field in xml using java. I used setTextContent() for this, but the xml file is not getting updated.
here is my java code:
public static void main(String argv[]) {
DisclosureTranslation dt=new DisclosureTranslation();
String filepath="E:\\Repository\\17Nov_demo\\file.xml";
dt.getHashmap(filepath);
}
public void getHashmap(String filepath){
try {
DocumentBuilderFactory documentbuilderfactory=DocumentBuilderFactory.newInstance();
DocumentBuilder documentbuilder =documentbuilderfactory.newDocumentBuilder();
Document doc=documentbuilder.parse(filepath);
XPath xPath = XPathFactory.newInstance().newXPath();
Element element=doc.getDocumentElement();
NodeList nodelist=(NodeList)xPath.evaluate("/DOCUMENT/ishobject/ishfields/ishfield[#name='FHPIDISCLOSURELEVEL']",
doc.getDocumentElement(), XPathConstants.NODESET);
System.out.println(nodelist.item(0).getTextContent());
String val=nodelist.item(0).getTextContent();
//String val="111";
HashMap<String, String> hashmap=new HashMap<String,String>();
hashmap.put("47406819852170807613486806879990", "public");
hashmap.put("222"," HP Internal");
String value=hashmap.get(val);
nodelist.item(0).setTextContent(value);
System.out.println(nodelist.item(0).getTextContent());
}
the last line is displaying what i want. But its not getting reflected in the xml file. How am i suppose to update my xml file?
Thanks in advance! :)
Once you have updated the element from parsing the xml from the file path, update them to the same file using below method.
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult streamResult = new StreamResult(new File(filePath));
transformer.transform(source, streamResult);
Saving the xml back to the file can also be achieved by using "Transformer API".

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

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