Create XML from a / separated string - java

Following is a Map element
i need to create a xslt from this.
{ /output1/output1/output1/output13=/input12/bunny,
/output1/output1/output1/output14=/input12/no,
/output1/output1/output13/output12=/input12/ok,
/output1/output1/output13/output16=/input12/honey
}
how should i compare the each element of key element with each element of the next key element?
package mig;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Attr;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class CreateXSLT {
public static final String xmlFilePath = "D:/xmlfile.xml";
public void createXSLT(ArrayList<String> SourceValues,ArrayList<String> SourceTypes,ArrayList<String> TargetValues,ArrayList<String> TargetTypes,ArrayList<String> Transform)
{
try {
Map<String, String> yourMap = new HashMap<String, String>();
for(int x=0;x<TargetValues.size();x++)
{
yourMap.put(TargetValues.get(x),SourceValues.get(x));
}
Map<String, String> sortedMap = new TreeMap<String, String>(yourMap);
System.out.println(sortedMap);
Set<Entry<String, String>> entires =sortedMap.entrySet();
Set<String> keyset = sortedMap.keySet();
System.out.println(keyset);
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element root = document.createElement("xsl:stylesheet");
document.appendChild(root);
Element root1 = document.createElement("xsl:template");
root.appendChild(root1);
Attr attr = document.createAttribute("match");
attr.setValue("/");
root1.setAttributeNode(attr);
Element empDiffNxt = null;
Element empDiff = null;
int nodeLength = keyset.size();
System.out.println("TARGET sIZE: " + nodeLength);
for(String key : keyset)
{
ArrayList<String> check = new ArrayList<String>();
check.add(key);
String[] Tg = key.split("/");
for (int m=1; m< Tg.length; m++)
{
if( m == 1 )
{
empDiffNxt = document.createElement(Tg[m]);
root1.appendChild(empDiffNxt);
}
else
{
empDiff = document.createElement(Tg[m]);
empDiffNxt.appendChild(empDiff);
empDiffNxt= empDiff;
}
}
Element emp1 = document.createElement("xsl:value-of");
empDiffNxt.appendChild(emp1);
Attr attr1 = document.createAttribute("select");
attr1.setValue(sortedMap.get(key));
emp1.setAttributeNode(attr1);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File(xmlFilePath));
transformer.transform(domSource, streamResult);
System.out.println("Done creating XML File");
}
catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
this is the code i have written.....
This part is coming as a list inside Targetvalue
/output1/output1/output1/output13
/output1/output1/output1/output14
/output1/output1/output13/output12
/output1/output1/output13/output16
And
/input12/bunny
/input12/bunny
/input12/bunny
/input12/bunny
in the the list Source values
surce value and the target value has link.. means first value of source is connected with first value of target.. 2nd value of source connected with 2nd value of target.
<?xml version="1.0" encoding="UTF-8" standalone="no"?><xsl:stylesheet><xsl:template match="/"><output1><output1><output1><output13><xsl:value-of select="/input12/bunny"/></output13></output1></output1></output1><output1><output1><output1><output14><xsl:value-of select="/input12/no"/></output14></output1></output1></output1><output1><output1><output13><output12><xsl:value-of select="/input12/ok"/><xsl:value-of select="/input12/honey"/></output12></output13></output1></output1></xsl:template></xsl:stylesheet>
this is getting generated.........
but what i want is:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsl:stylesheet>
<xsl:template match="/">
<output1>
<output1>
<output1>
<output13>
<xsl:value-of select="/input12/bunny"/>
</output13>
<output14>
<xsl:value-of select="/input12/no"/>
</output14>
</output1>
<output13>
<output12>
<xsl:value-of select="/input12/ok"/>
</output12>
<output16>
<xsl:value-of select="/input12/honey"/>
</output16>
</output13>
</output1>
</output1>

Related

Updating an XML in Java

I am trying to change the PlannedDuration of Activity A04 but I have not been able to see the changes in the XML file. The changes are not updated into the file. I do not know what I am doing wrong.
The XML is too long. The file has information about several activities. I am interested only in the activity with Id A04.
The initial value of the PlannedDuration is 16 and I changed it to 25.
XML File:
package modifyXML;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ModifyXML{
public static void main(String[] args) {
File xmlfile = new File("C:/Users/dianitaf/Downloads/xml Files/CS_1.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document document = dBuilder.parse(xmlfile);
document.getDocumentElement().normalize();
updateElementValue(document,"Id", "A04");
document.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File("xmlfile"));
transformer.transform(source, result);
System.out.println("XML file updated successfully");
} catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {
e1.printStackTrace();
}
}
private static void updateElementValue(Document document, String textNodeName, String textNodeValue) {
NodeList Activity = document.getElementsByTagName("Activity");
Element act = null;
//loop for each activity
for(int i=0; i<Activity.getLength();i++){
Node activityNode = Activity.item(i);
if(activityNode.getNodeType() == Node.ELEMENT_NODE)
{
Element activityElement = (Element) activityNode;
NodeList textNodes = activityElement.getElementsByTagName(textNodeName);
if(textNodes.getLength() > 0)
{
if(textNodes.item(0).getTextContent().equalsIgnoreCase(textNodeValue))
{
System.out.println(textNodes.item(0).getTextContent());
System.out.println(activityElement.getElementsByTagName("Name").item(0).getTextContent());
act = (Element) Activity.item(i);
Node duration = act.getElementsByTagName("PlannedDuration").item(0).getFirstChild();
System.out.println("Initial Duration : " + act.getElementsByTagName("PlannedDuration").item(0).getTextContent()); act.getElementsByTagName("PlannedDuration").item(0).getTextContent();
duration.setTextContent("25");
System.out.println("Updaded Duration : " + act.getElementsByTagName("PlannedDuration").item(0).getTextContent());
}
}
}
}
}
}
XML:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><APIBusinessObjects>
<ProjectList>
<Project ObjectId="4627">
<Id>CS_1</Id>
<Name>Case Study No.1 Warehouse Project - CPM</Name>
</Project>
</ProjectList>
<Project>
<Activity>
<Id>A04</Id>
<Name>Nailers to Purlins</Name>
<PlannedDuration>16</PlannedDuration>
<StartDate>2018-12-26Te8:00:00</StartDate>
</Activity>
</Project>
</APIBusinessObjects>
Java:
package modifyXML;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ModifyXML {
public static void main(String[] args) {
File xmlfile = new File("D:\\delete\\test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document document = dBuilder.parse(xmlfile);
document.getDocumentElement().normalize();
updateElementValue(document, "Id", "A04");
document.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(xmlfile);
transformer.transform(source, result);
System.out.println("XML file updated successfully");
} catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {
e1.printStackTrace();
}
}
private static void updateElementValue(Document document, String textNodeName, String textNodeValue) {
NodeList Activity = document.getElementsByTagName("Activity");
Element act = null;
// loop for each activity
for (int i = 0; i < Activity.getLength(); i++) {
Node activityNode = Activity.item(i);
if (activityNode.getNodeType() == Node.ELEMENT_NODE) {
Element activityElement = (Element) activityNode;
NodeList textNodes = activityElement.getElementsByTagName(textNodeName);
if (textNodes.getLength() > 0) {
if (textNodes.item(0).getTextContent().equalsIgnoreCase(textNodeValue)) {
System.out.println(textNodes.item(0).getTextContent());
System.out.println(activityElement.getElementsByTagName("Name").item(0).getTextContent());
act = (Element) Activity.item(i);
Node duration = act.getElementsByTagName("PlannedDuration").item(0).getFirstChild();
System.out.println("Initial Duration : "
+ act.getElementsByTagName("PlannedDuration").item(0).getTextContent());
act.getElementsByTagName("PlannedDuration").item(0).getTextContent();
duration.setTextContent("25");
System.out.println("Updaded Duration : "
+ act.getElementsByTagName("PlannedDuration").item(0).getTextContent());
}
}
}
}
}
}

Read from folder and update the XML tag value

I have a folder("Container") inside this i have some .txt files which actually contains XML. All files have a common element <Number> which i want to increment by 1 for all the XML files.
any help.
i have done the change for a single .txt file, which is okay:-
package ParsingXML;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class ReadAndModifyXMLFile {
public static final String xmlFilePath = "C:\\Users\\PSINGH17\\Desktop\\testFile.txt";
public static void main(String argv[]) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(xmlFilePath);
// Get employee by tag name
//use item(0) to get the first node with tag name "employee"
Node employee = document.getElementsByTagName("employee").item(0);
// update employee , increment the number
NamedNodeMap attribute = employee.getAttributes();
Node nodeAttr = attribute.getNamedItem("number");
String str= nodeAttr.getNodeValue();
System.out.println(str);
int val= Integer.parseInt(str);
System.out.println(val);
val=val+1;
System.out.println(val);
String final_value= String.valueOf(val);
System.out.println(final_value);
nodeAttr.setTextContent(final_value);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File(xmlFilePath));
transformer.transform(domSource, streamResult);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
}
xml file:-
<?xml version="1.0" encoding="UTF-8" standalone="no"?><company>
<employee number="14">
<firstname>Pranav</firstname>
<lastname>Singh</lastname>
<email>pranav#example.org</email>
<salary>1000</salary>
</employee>
</company>
So this code uses the initial value digits after hash to start the counter.
Then it iterates through all the files in the folder.
The first file will get the initial value, the rest will get incremented values.
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
public class TestFile {
public static final String xmlFileFolder = "C:\\Rahul\\test";
private static final String initialValue = "450-000-1212";
public static void main(String argv[]) {
int baseValue = Integer.parseInt(getValueAfterLastDash(initialValue));
System.out.println("startValue " + baseValue);
File folder = new File(xmlFileFolder);
for (File file : folder.listFiles()) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
Node employee = document.getElementsByTagName("employee").item(0);
NamedNodeMap attribute = employee.getAttributes();
Node nodeAttr = attribute.getNamedItem("number");
System.out.println(getValueBeforeLastDash(initialValue) + baseValue);
nodeAttr.setTextContent(getValueBeforeLastDash(initialValue) + baseValue);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(file);
transformer.transform(domSource, streamResult);
baseValue++;
} catch (Exception ignored) {
}
}
}
private static String getValueAfterLastDash(String initialValue) {
return initialValue.substring(initialValue.lastIndexOf('-') + 1, initialValue.length());
}
private static String getValueBeforeLastDash(String initialValue) {
return initialValue.substring(0, initialValue.lastIndexOf('-') + 1);
}
}

How to write Multiple Element in the XML using JAVA

Sample XML which i have to generate using JAVA
sense
168
192.168.140.150
002EC0FEFF83EA97
Code Used I have written so far
import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class SampleCode {
public static final String xmlFilePath = "C:\\Users\\harsh.sharma\\Desktop\\Sense Performance\\Generated\\xmlfile.xml";
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
try {
String cid_Value="168";
String ip_Value="192.168.140.150";
String id_Value="002EC0FEFF83EA97";
String sensorsid_Value="002EC0FEFF8FFF27";
String desc_Value=" ";
String batt_Value="6.60";
String sig_Value="-55";
String scount_Value="0";
String rdate_Value="15/05/2015 21:47:04";
DateFormat dateFormat = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss");
//get current date time with Date()
#SuppressWarnings("deprecation")
Calendar cal = Calendar.getInstance();
String mdate_Value=dateFormat.format(cal.getTime());
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
//root element
Element root = document.createElement("msgs");
document.appendChild(root);
//msg element
Element msg = document.createElement("msg");
root.appendChild(msg);
//type element
Element type = document.createElement("type");
msg.appendChild(type);
type.setTextContent("Sense");
//cid element
Element cid = document.createElement("cid");
msg.appendChild(cid);
cid.setTextContent(cid_Value);
//ip element
Element ip = document.createElement("ip");
msg.appendChild(ip);
ip.setTextContent(ip_Value);
Element errs = document.createElement("errs");
msg.appendChild(errs);
//id element
Element id = document.createElement("id");
msg.appendChild(id);
id.setTextContent(id_Value);
//sensors element
Element sensors = document.createElement("sensors");
msg.appendChild(sensors);
//Sensor element
Element sensor = document.createElement("sensor");
//sensors.appendChild(sensor);
sensor.setAttribute("sensorsid",sensorsid_Value);
sensor.setAttribute("desc",desc_Value);
sensor.setAttribute("batt",batt_Value);
sensor.setAttribute("sig", sig_Value);
sensor.setAttribute("scount",scount_Value);
sensor.setAttribute("rdate",rdate_Value);
sensor.setAttribute("mdate",mdate_Value);
sensors.appendChild(sensor);
// create the xml file
//transform the DOM Object to an XML File
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File(xmlFilePath));
// If you use
// StreamResult result = new StreamResult(System.out);
// the output will be pushed to the standard output ...
// You can use that for debugging
transformer.transform(domSource, streamResult);
System.out.println("Done creating XML File");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
I want it should give me multiple rows under the sensor Element, I want to write the loop that I can generate multiple data for the sensor Element

Trying to build XML file with iterator in java

Ive written some code that creates an XML file from my System Properties in java. It works exactly how I want it to but I really (really) dont like how I ended up just using like 5 if statements to get it to work since I noticed none of the properties go beyond 4 delimited substrings anyways.
Id much prefer using an iterator and some kind of hasNext() method to continue appending onto elements until the end of the string but I couldn't work anything out.
I couldn't find a way to append the newest tag onto the last one in a loop/ add the value to the end of the elements.
This is what I currently have as a quick fix to get the program running.
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("JAVA");
doc.appendChild(rootElement);
Iterator it = hm.entrySet().iterator();
while (it.hasNext())
{
Map.Entry entry = (Map.Entry) it.next();
String keyString = (String)entry.getKey();
String val = (String)entry.getValue();
java.util.List<String> sa = Arrays.asList(keyString.split("\\."));
Iterator ait = sa.iterator();
Element tag = doc.createElement((String) ait.next());
rootElement.appendChild(tag);
Element tag2 = null;
Element tag3 = null;
Element tag4 = null;
Element tag5 = null;
while(ait.hasNext())
{
if(ait.hasNext())
{
tag2 = doc.createElement((String)ait.next());
tag.appendChild(tag2);
if(!ait.hasNext())
tag2.appendChild(doc.createTextNode(val));
}
if(ait.hasNext())
{
tag3=doc.createElement((String)ait.next());
tag2.appendChild(tag3);
if(!ait.hasNext())
tag3.appendChild(doc.createTextNode(val));
}
if(ait.hasNext())
{
tag4=doc.createElement((String)ait.next());
tag3.appendChild(tag4);
if(!ait.hasNext())
tag4.appendChild(doc.createTextNode(val));
}
if(ait.hasNext())
{
tag5=doc.createElement((String)ait.next());
tag5.appendChild(tag5);
if(!ait.hasNext())
tag5.appendChild(doc.createTextNode(val));
}
}
}
Transformer transformer = null;
TransformerFactory transformerFactory = TransformerFactory.newInstance();
try
{
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("XMLtester"));
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(source, result);
} catch (TransformerConfigurationException e)
{
e.printStackTrace();
} catch (TransformerException e)
{
e.printStackTrace();
}
catch(NullPointerException e)
{
System.out.println("ERROR: " + e.toString());
}
System.out.println("File saved!");
If anyone has any ideas on how to make this a little more flexible or elegant so as to take in any number of delimited substrings id appreciate it.
I think this is what you want.
Element destination = rootElement;
Element tag = null;
while (ait.hasNext()) {
tag = doc.createElement((String) ait.next());
destination.appendChild(tag);
destination = tag;
}
destination.appendChild(doc.createTextNode(val));
Example output:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<JAVA>
<java>
<runtime>
<name>Java(TM) SE Runtime Environment</name>
</runtime>
</java>
<sun>
<boot>
<library>
<path>/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home/jre/lib</path>
</library>
</boot>
</sun>
<java>
<vm>
<version>23.0-b19</version>
</vm>
</java>
<user>
<country>
<format>GB</format>
</country>
</user>
Full working example:
import java.io.File;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class StackOverflow23556822 {
public static void main(String[] args) throws ParserConfigurationException,
TransformerException {
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("JAVA");
doc.appendChild(rootElement);
Iterator<?> it = System.getProperties().entrySet().iterator();
while (it.hasNext()) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) it.next();
String keyString = (String) entry.getKey();
String val = (String) entry.getValue();
List<String> sa = Arrays.asList(keyString.split("\\."));
Iterator<?> ait = sa.iterator();
Element destination = rootElement;
Element tag = null;
while (ait.hasNext()) {
tag = doc.createElement((String) ait.next());
destination.appendChild(tag);
destination = tag;
}
destination.appendChild(doc.createTextNode(val));
}
Transformer transformer = null;
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("xml-test.xml"));
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(source, result);
System.out.println("File saved!");
}
}

I can't edit a node content into an XML file with Java

I'm trying to edit an XML file with Java, the thing is that I need to edit the content & replace them by what I want inside
(I want to replace some nodes that are in Deutsh into French
[for expample <fr>DE1</fr> into <fr>FR1</fr>])
I tried to use :
node.setTextContent(Value);
node.setNodeValue(Value);
But it doesn't work at all
Is there any other function that might work in editing these nodes below ?
Here's the code :
for (int i = memory; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if ((langu.equals(node.getNodeName()))) //langu = "fr"
{
test = node.getTextContent();
if(isCorrect()){}
else if ((manualTr.clickCount >= 0)
){
trash = test;
node.setTextcontent(Value);
// node.setNodeValue("Test");
memory += manualTr.clickCount;
manualTr.clickCount -= 1;
}
}
}
And here's the XML code :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<titles>
<tome>
<de>DE1</de>
<fr>DE1</fr>
<en>EN1</en>
</tome>
<valhalla>
<de>DE2</de>
<fr>DE2</fr>
<en>EN2</en>
</valhalla>
<vikings>
<de>DE3</de>
<fr>DE3</fr>
<en>EN3</en>
</vikings>
</titles>
Try this.. I am using setTextContent() to update a node value.
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* #author JayaPrasad
*
*/
public class ParseXml {
public static void main(String[] args) {
System.out.println("Started XML modification");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
Document xmlDoc;
xmlDoc = docBuilder.parse(new File("sample.xml"));
NodeList nodes = xmlDoc.getElementsByTagName("fr");
for (int i = 0, length = nodes.getLength(); i < length; i ++) {
((Element)nodes.item(i)).setTextContent("Modified");
}
xmlDoc.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource domSource = new DOMSource(xmlDoc);
StreamResult result = new StreamResult(new File("sample.xml"));
transformer.transform(domSource, result);
System.out.println("Modification Done");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Categories