how to update XML data from java - 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".

Related

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

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?

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.

Convert JTree to XML

I've seen many many articles on how to read XML into a JTree but few on how to create the XML from the JTree. Can anyone help me with a simple approach for this? I've seen an example that looked like:
XMLEncoder e = new XMLEncoder(
new BufferedOutputStream(new FileOutputStream(f.toString())));
e.writeObject(o);
e.close();
.. but I can't get this to work; it returns an XML file but its not quite right, looking like this:
<java version="1.6.0_17" class="java.beans.XMLDecoder">
<object class="javax.swing.JTree">
<object class="javax.swing.tree.DefaultTreeModel">
<object class="javax.swing.tree.DefaultMutableTreeNode">
<void property="userObject">
.. etc, but with none of my data in there.
(PS: Please be gentle, I'm very new to java!)
The XMLEncoder is a generic utility for encoding beans as text. I don't think it is suitable in your case.
I wrote a piece of code that does the job, assuming that I understand well your needs. You only have to pass the tree model as a parameter to the toXml method. Note that this is just a draft; You will probably want to handle exceptions differently, and manage your transformation parameters differently. More important, you can manipulate the recursive createTree method in order to change the structure of the XML node created per tree node.
public static String toXml(TreeModel model) throws ParserConfigurationException, TransformerException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
// Build an XML document from the tree model
Document doc = impl.createDocument(null,null,null);
Element root = createTree(doc, model, model.getRoot());
doc.appendChild(root);
// Transform the document into a string
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
return sw.toString();
}
private static Element createTree(Document doc, TreeModel model, Object node) {
Element el = doc.createElement(node.toString());
for(int i=0;i<model.getChildCount(node);i++){
Object child = model.getChild(node, i);
el.appendChild(createTree(doc,model,child));
}
return el;
}

Categories

Resources