JAVA Read XML file and modify attribute values based on some conditions
I have the following XML file "C:/Data.xml".
If the attributes on Dimension, Metirc, Data date Matches then Add the amount values and remove the duplicate DS node.
I looked some examples on hashtable/hashmapping but I could not find that meets my creiteria. I appriciate any direction or suggestions on this.
<ED LG="US">
<DS name="1" source="A" freq="Day">
<Dimension name="code" value="3">
<Metric ref_name="A1-ACT">
<Data date="2011-03-04T00:00:00" amount="30" />
</Metric>
</Dimension>
</DS>
<DS name="1" source="A" freq="Day">
<Dimension name="code" value="3">
<Metric name="A1-ACT">
<Data date="2011-03-04T00:00:00" amount="40" />
</Metric>
</Dimension>
</DS>
<DS name="1" source="A" freq="Day">
<Dimension name="code" value="3">
<Metric name="A1-ACT">
<Data date="2011-03-05T00:00:00" amount="20" />
</Metric>
</Dimension>
</DS>
</ED>
Expected Result:
<ED LG="US">
<DS name="1" source="A" freq="Day">
<Dimension name="code" value="3">
<Metric ref_name="A1-ACT">
<Data date="2011-03-04T00:00:00" amount="70" />
</Metric>
</Dimension>
</DS>
<DS name="1" source="A" freq="Day">
<Dimension name="code" value="3">
<Metric name="A1-ACT">
<Data date="2011-03-05T00:00:00" amount="20" />
</Metric>
</Dimension>
</DS>
</ED>
thanks
Edited by: user7188033 on Mar 19, 2011 1:40 PM
Edited by: user7188033 on Mar 19, 2011 2:01 PM
Edited by: user7188033 on Mar 19, 2011 2:02 PM
Use XSLT for transforming the XML document.
Similar Messages
-
CS4-JS : Read XML file and getting Attributes
Dear All,
How to get the Attributes based on the RootElements.
For Example:
//========================== XML File : Start ================================//
<stag>
<cust>
<custname>120</custname>
<atagst name="alpha" attributename="1" attributevalue="2" sty="First"/>
<atagst name="beta" attributename="1" attributevalue="5" sty="Second"/>
<atagst name="gama" attributename="1" attributevalue="2" sty="Third"/>
<atagst name="theta" attributename="1" attributevalue="5" sty="Fourth"/>
<cust>
<cust>
<custname>121</custname>
<atagst name="A.alpha" attributename="1" attributevalue="2" sty="First"/>
<atagst name="A.beta" attributename="1" attributevalue="5" sty="Second"/>
<atagst name="A.gama" attributename="1" attributevalue="2" sty="Third"/>
<atagst name="A.theta" attributename="1" attributevalue="5" sty="Fourth"/>
<cust>
<cust>
<custname>122</custname>
<atagst name="B.alpha" attributename="1" attributevalue="2" sty="First"/>
<atagst name="Bbeta" attributename="1" attributevalue="5" sty="Second"/>
<atagst name="B.gama" attributename="1" attributevalue="2" sty="Third"/>
<atagst name="B.theta" attributename="1" attributevalue="5" sty="Fourth"/>
<cust>
</stag>
//========================== XML File : End ================================//
Here I want to check through Java Script Code [InDesign]
//======================== Script : Starts ====================================//
var myEveryName = new Array();
traverse(roots);
for(var Element_name=0; Element_name<myEveryName.length; Element_name++)
if(myEveryName[Element_name] == "customername")
custname.push(myEveryContent[Element_name]);
if(myEveryName[Element_name] == "applytagstyle")
Aname.push(myEveryAttributes[Element_name][0]);
Aattributename.push(myEveryAttributes[Element_name][1]);
Aattributevalue.push(myEveryAttributes[Element_name][2]);
Asty.push(myEveryAttributes[Element_name][3]);
function traverse(tree) {
myEveryName.push(tree.name());
if(tree.elements().length() > 0) {
for(var i=0; i<tree.elements().length(); i++) {
traverse(tree.elements()[i]);
//======================== XML File : End ====================================//
Everything working fine, but I couldn't get attribute values. Please check the below example
For Example:
If you check first root element in above xml code
i need the output like
custname=120
name=alpha,beta,gama,theta
attributename=1,1,1,1
attributevalue=2,5,2,5
sty=first,second,third,fourth
custname=121
Please any one can help me and give me the solutions.
Thanks & Regards
T.R.Harihara SudhaNFew questions:
1. Your XML is not well formed.
2. Secondly, I do not see any relation of XML with script. For instance, I do see any elements "customername", "applytagstyle" in input.
3. Either you have not provided the complete source or either your dummy XML is incorrect.
Anyways, having a quick look, I guess you are trying to get specific attributes values from XML tree. I will try to give you a kick start though you will be required to customized the script as per requirement (for instance rearranging the attribute values in array and so forth). Otherwise please try to post complete inputs.
#include "glue code.jsx"
//Get the attribute values of all elements
main();
function main(){
if (app.documents.length != 0){
var myDoc = app.activeDocument;
var myRuleSet = new Array (
new findObjAttribute("//*")
with(myDoc){
var elements = xmlElements;
__processRuleSet(elements.item(0), myRuleSet);
else{
alert("You have no document open!");
exit();
function findObjAttribute(XPATH){
this.name = "findObjAttribute";
this.xpath = XPATH;
this.apply = function(myElement, myRuleProcessor)
var elmName=myElement.markupTag.name;
with(myElement){
try {
var Name=myElement.xmlAttributes.itemByName("name").value;
var AttName=myElement.xmlAttributes.itemByName("attributename").value;
var AttValue=myElement.xmlAttributes.itemByName("attributevalue").value;
var AttSty=myElement.xmlAttributes.itemByName("sty").value;
$.writeln("Name: "+Name);
$.writeln("AttributeName: "+AttName);
$.writeln("AttributeValue: "+AttValue);
$.writeln("Sty: "+AttSty);
} catch(e){};
return true;
This will just print the values JavaScript console.
HTH,
Pankaj Chaturvedi -
Please recommend if we have options to read xml file and insert data into table without a temporary table.
DECLARE @data XML;
SET @data =N'<Root>
<List RecordID="946236" />
<List RecordID="946237" />
<List RecordID="946238" />
<List RecordID="946239" />
<List RecordID="946240" />
</Root>'
INSERT INTO t (id) SELECT T.customer.value('@RecordID', 'INT') AS id
FROM @data.nodes('Root/List')
AS T(customer);
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
How to read XML file and update the data in MS CRM 2011?
Hi Folks,
Can anyone please help me finding some references to read XML files and push the data to MS CRM 2011 preferably by using a console application.
Please let me know if any ways of handling it in simple ways.
Thanks,
SriHI,
How to read XML file:
https://social.msdn.microsoft.com/Forums/en-US/5dd7261b-86c4-4ca8-ba87-95196ef3ba50/need-to-display-xml-file-in-textboxes-edit-the-data-and-save-the-new-xml-file?forum=csharpgeneral
How to work with CRM:
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = new System.Net.NetworkCredential("USER", "Password", "Domain");
Uri uri = new Uri("http://server/Organization/XRMServices/2011/Organization.svc");
OrganizationServiceProxy proxy = new OrganizationServiceProxy(uri, null, credentials, null);
proxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
IOrganizationService service = (IOrganizationService)proxy;
//using "service" you can create, update and retrieve entities.
More information here about service functions:
https://msdn.microsoft.com/en-us/library/gg328198.aspx -
Hello All,
anybody have a procedure to open a XML file and modify some os that tags and after save it at a local file or a server?
Best Regards,
RicardoRicardo,
Take a look at this simple transformation example,
http://help.sap.com/abapdocu_70/en/ABENABAP_ST_EXAMPLE.htm
http://wiki.sdn.sap.com/wiki/display/Snippets/XMLXLStransformation
http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/a89312f8-0b01-0010-86b3-fdd7178e0534
Last, but not least take a look at the blog series here in SDN.. He has a five part series for XML processing in ABAP...
/people/tobias.trapp/blog/2005/05/04/xml-processing-in-abap-part-1 -
Reading XML file and skip certain elements/attributes??
Hi folks!
Suppose I have a XML file looking like this:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dvds SYSTEM "DTDtest.dtd">
<dvds>
<dvd>
<title>
Aliens
</title>
<director>
James Cameron
</director>
<format>
1.85:1
</format>
</dvd>
<dvd>
<title>
X-Men
</title>
<director>
Bryan Singer
</director>
<format>
2.35:1
</format>
</dvd>
</dvds>
In my Java application I want to read this XML file and print it on the screen (including all tags etc). So far, so good. BUT, if I want to skip certain elements, i.e. all information about the dvd 'X-Men', how am I supposed to do this? In other words, I would like my app to skip reading all information about X-Men and continue with the next <dvd>... </dvd> tag. Is this possible?
My code so far is from the XML tutorial from Sun and it looks like this:
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
public class MyXML extends DefaultHandler
public static void main(String argv[]) {
if (argv.length != 1) {
System.err.println("Usage: cmd filename");
System.exit(1);
// Use an instance of ourselves as the SAX event handler
DefaultHandler handler = new MyXML();
// Use the default (non-validating) parser
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
// Set up output stream
out = new OutputStreamWriter(System.out, "UTF8");
// Parse the input
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( new File(argv[0]), handler);
} catch (Throwable t) {
t.printStackTrace();
System.exit(0);
static private Writer out;
//===========================================================
// SAX DocumentHandler methods
//===========================================================
public void startDocument()
throws SAXException
emit("<?xml version='1.0' encoding='UTF-8'?>");
nl();
public void endDocument()
throws SAXException
try {
nl();
out.flush();
} catch (IOException e) {
throw new SAXException("I/O error", e);
* <p>This method prints the start elements including attr.
* @param namespaceURI
* @param lName
* @param qName
* @param attrs
* @throws SAXException
public void startElement(String namespaceURI,
String lName, // local name
String qName, // qualified name
Attributes attrs)
throws SAXException
String eName = lName; // element name
if ("".equals(eName)) eName = qName; // namespaceAware = false
emit("<"+eName);
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String aName = attrs.getLocalName(i); // Attr name
if ("".equals(aName)) aName = attrs.getQName(i);
emit(" ");
emit(aName+"=\""+attrs.getValue(i)+"\"");
emit(">");
public void endElement(String namespaceURI,
String sName, // simple name
String qName // qualified name
throws SAXException
emit("</"+qName+">");
* <p>This method prints the data between 'tags'
* @param buf
* @param offset
* @param len
* @throws SAXException
public void characters(char buf[], int offset, int len)
throws SAXException
String s = new String(buf, offset, len);
emit(s);
//===========================================================
// Utility Methods ...
//===========================================================
// Wrap I/O exceptions in SAX exceptions, to
// suit handler signature requirements
private void emit(String s)
throws SAXException
try {
out.write(s);
out.flush();
} catch (IOException e) {
throw new SAXException("I/O error", e);
// Start a new line
private void nl()
throws SAXException
String lineEnd = System.getProperty("line.separator");
try {
out.write(lineEnd);
} catch (IOException e) {
throw new SAXException("I/O error", e);
Sorry about the long listing... :)
Best regards
/PaulA possibility that comes to mind is to create an XSLT script to do whatever it is you want - and call it from inside the program. The XSLT script can be stashed inside your .jar file by using getClass().getClassLoader().getResource("...")
- David -
How to read XML file and write into another XML file
Hi all, I am new to JAVAXML.
My problem is I have to read one XML file and take some Nodes from that and write these nodes into another XML file...
I solved, how to read XML file
But I don't know how to Write nodes into another XML.
Can anyone help in this???
Thanks in advance..This was answered a bit ago. There was a thread called "XML Mergine" that started on Sept 14th. It has a lot of information about what it takes to copy nodes from one XML Document object into another.
Dave Patterson -
Code to read xml file and display that data using sax parser
Hai
My problem I have to read a xml file and display the contents of the file on console using sax parser.here you go
-
How to read xml file and place it into an internal table...
hello all,
can any one help me in - how to read xml data file (placed in application server) and placing the same into an internal table (remove the xml tags or say fetching the xml data without xml tags).Hi Murashali,
use this.
TYPES: BEGIN OF day,
name TYPE string,
work(1) TYPE c,
END OF day.
DATA: BEGIN OF week,
day1 TYPE day,
day2 TYPE day,
day3 TYPE day,
day4 TYPE day,
day5 TYPE day,
day6 TYPE day,
day7 TYPE day,
END OF week.
DATA xml_string TYPE string.
DATA result LIKE week.
week-day1-name = 'Monday'. week-day1-work = 'X'.
week-day2-name = 'Tuesday'. week-day2-work = 'X'.
week-day3-name = 'Wednesday'. week-day3-work = 'X'.
week-day4-name = 'Thursday'. week-day4-work = 'X'.
week-day5-name = 'Friday'. week-day5-work = 'X'.
week-day6-name = 'Saturday'. week-day6-work = ' '.
week-day7-name = 'Sunday'. week-day7-work = ' '.
CALL TRANSFORMATION ...
SOURCE root = week
RESULT XML xml_string.
CALL TRANSFORMATION ...
SOURCE XML xml_string
RESULT root = result.
Regards,
Vijay -
How to Read Xml File and view into Data Grid View?
hi all
my Data into Xml file are:
<Voucher>
<Header>
<txtHeaderId>259803</txtHeaderId>
<txtDate>2015/02/01</txtDate>
<txtDocNo>20</txtDocNo>
<txtMemo>This is a Test .</txtMemo>
</Header>
<Item>
<txtItemId>8562803</txtItemId>
<txtHeaderRef>259803</txtHeaderRef>
<txtDesc>This is Number 1</txtDesc>
<txtDebit>350000</txtDebit>
<txtCredit>0</txtCredit>
<txtItemId>8562804</txtItemId>
<txtHeaderRef>259803</txtHeaderRef>
<txtDesc>This is Number 2</txtDesc>
<txtDebit>0</txtDebit>
<txtCredit>350000</txtCredit>
</Item>
</Voucher>
now i have two DataGridViews
i want that data from xml file show into the DataGridViews by this codes:
Private Sub btnReadXmlFile_Click(sender As Object, e As EventArgs) Handles btnReadXmlFile.Click
Dim Document As XmlReader = New XmlTextReader(txtPath.Text)
Dim ds As New DataSet
ds.ReadXml(Document)
DataGridView1.DataSource = ds.Tables(0)
End Sub
but i see this result:
why i do not see any result into DataGridView2(Item)
how to solve it ?
please help me .
thanks all
Name of Allah, Most Gracious, Most Merciful and He created the humannow how to correct it?
Name of Allah, Most Gracious, Most Merciful and He created the human
Please be explicit - I'm the only other one in this thread so I assume it's to me, but usually I just ignore the posts when the user isn't specific.
I don't know what there is to correct. Create a NEW dataset in code, add the two tables, and use the methods that I suggested.
I'm not a database guy so I can't get real specific. I create my own stuff in classes and use that but, if you're using SQL then there are lots of pro's here that can help you with specifics. I'm sure they'll need to know a lot more about your data, the
connection, and all that, but the concept should be fairly simple to implement.
Still lost in code, just at a little higher level. -
Read XML file and generate a XLS file?
Hi Guys,
How I can generate a XLS file with information in a XML file.
I have a XML which received information from a form.
To the user see the information inside a XML file, I created a report.cfm with the informations of the users.
Now the user want which the information in the XML, generate a XLS file from a CFM file to download.
How I will transformed this information in a XLS file?
Thanks,
Fabiano Magno PechibellaThere is no need to re-invent the wheel. Raymond Camden has published code that converts information from a form to an Excel file. His method first converts information from a form to a query. But you can easily adapt it to your case. If you do not have direct access to the form, you will still be able to convert the XML data into the name-value pairs in the query.
-
Take an existing text file and modify values
I’m looking to take an existing text file and modify certain values inside of it. Then save it to a new file, with all the same formatting as the original. The file format is not uniform and can change.
Basically the file is:
Random numbers and letters of unknown length for an unknown number of lines.
Label="Test_#"
Description
String
X=123
Y=456
Z=-789
20 lines of strings with numbers in them
Label="Test_#2"
Description
String
X=-1232
Y=4562
Z=7892
Then it repeats a set number of times.
I want to modify the X Y and Z = values for each Test_#.
I’ve managed to import the important values into a numeric array and I have a different array with values that will replace the existing ones. I’m having troubles replacing the existing ones. There are no zeros before or after the existing numbers so they are all different lengths.
If anyone has any sample code that does anything similar please post it. I’m sure someone has done something like this in the past.
Solved!
Go to Solution.I just thought I would throw this out there. Can you make the .txt file tokenized? This would make searching for specific parameters much easier.
Reese, (former CLAD, future CLD)
Some people call me the Space Cowboy!
Some call me the gangster of love.
Some people call me MoReese!
...I'm right here baby, right here, right here, right here at home -
Reading an XML file and write the contents to another xml file in java
Hi,
I am new to xml parsing.My requirement is that I am getting a message (xml) using ibm MQ in the ByteArrayInputStream format.I have to read this xml message and write to another file.
I am creating a POC for this.
First I used simple reading and writing concept but the output is "java.io.FileInputStream@3e25a5 "
Sample xml file
- <Client>
<ClientId>1234</ClientId>
<ClientName>STechnology</ClientName>
<DTU_ID>567</DTU_ID>
<ClientStatus>ACTIVE</ClientStatus>
- <LEAccount>
<ClientLE>678989</ClientLE>
<LEId>56743</LEId>
- <Account>
<AccountNumber>9876543678</AccountNumber>
</Account>
</LEAccount>
- <Service>
<Cindicator>Y2Y</Cindicator>
<PrefCode>980</PrefCode>
<BSCode>876</BSCode>
<MandatoryContent>MSP</MandatoryContent>
</Service>
</Client>
code:
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ByteArrayInputStreamToXml {
public static void main(String srg[]) throws IOException{
InputStream inputStream= new FileInputStream("C:\\soft\\test2\\sample1.xml");
byte currentXMLBytes[] = inputStream.toString().getBytes();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(currentXMLBytes);
OutputStream out = new FileOutputStream("C:\\soft\\test\\data.xml");
int read=0;
byte[] bytes = new byte[1024];
while((read = byteArrayInputStream.read(bytes))!= -1){
out.write(bytes, 0, read);
out.write( '\n' );
inputStream.close();
out.flush();
out.close();
System.out.println("New file created!");
Please suggest me how can I use DOM/SAX parser ,I can see several code on net for reading xml file using SAX/DOM parser but writing an xml file after reading it using ByteArrayInputStream I am not getting .A help through some example Link will also be helpful for me.
Thanks
Sumit
Edited by: user8687839 on Apr 30, 2012 2:37 AM
Edited by: user8687839 on Apr 30, 2012 2:43 AMThanks I got the result.
package com.sumit.collections;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ByteArrayInputStreamToXml {
public static void main(String srg[]) throws IOException{
InputStream inputStream= new FileInputStream("C:\\soft\\test2\\sample1.xml");
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead; byte[] data = new byte[1024];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead); } buffer.flush();
byte currentXMLBytes[]= buffer.toByteArray();
/* byte currentXMLBytes[] = inputStream.toString().getBytes();*/
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(currentXMLBytes);
OutputStream out = new FileOutputStream("C:\\soft\\test\\data.xml");
int read=0;
byte[] bytes = new byte[1024];
while((read = byteArrayInputStream.read(bytes))!= -1){
out.write(bytes, 0, read);
out.write( '\n' );
inputStream.close();
out.flush();
out.close();
System.out.println("New file created!");
} -
Reading the datas in the Xml file and store it in the array using java
Hi every one
Can any one send me the java coding for traversing through XML file and get the data and store it in the array (SAX parser is prefered)
its a urgent requirement . please help me
Regards
Aruni send it to ur mail id ,
could you please send me a mail to [email protected] -
Reading data From XML file and setting into ViewObject to Pouplate ADF UI
Hi,
I have following requirement.
I would like to read data from XML file and populate the data in ViewObject so that the data can be displayed in the ADF UI.
Also when user modifies the data in the ADF UI, it should be modified back into to ViewObject.
Here is an example - XML file contains Book Title and Author. I would like to read Book Title and Author from XML file and set it into ViewObject Attribute and then display Book title and Author in ADF UI page. Also when user modifies Book title and Author, I would like to store it back in View Object.
Please help me with this requirement and let me know if any solution exist in ADF, for populating the ADF UI screen fields with external XML file data.
ThanksRead chapter 42 http://download.oracle.com/docs/cd/E16162_01/web.1112/e16182/bcadvvo.htm of the fusion developer guide
Section 42.7, "Reading and Writing XML"
Section 42.8, "Using Programmatic View Objects for Alternative Data Sources"
Timo
Maybe you are looking for
-
How to Display Grid in ORacle Forms
Hi Friends and Experts I have a requirement to display the records in Grid in ORacle Forms. This grid is a kind of Java grid. Help on this or any reference material for implementing this would be grately appreciated. Thanks in Advance. Ahmed
-
Work with no batery...
Can I work on my Macbook Pro with no batery? only conect to AC adapter? It's bad to the hardware?
-
Problems using JNI and JSP in WebLogic 6.0
Hello everybody. My problem is that I've got a Java class that is called from a JSP. That class connects to a C function and it returns a String. A want this string to be shown by the JSP. The code is: JSP <html> <head> <title>prueba JNI</title> </he
-
I cannot get my computer out of target disk mode
I had my G4 power Mac (10.4.11) connected in Target Disk Mode to my new Mac Mini (10.7.3) to migrate the file from it to the new Mini. Now I cannot get the old machine to go back into startup disk mode, it is staying in Targer Disk Mode. Any ideas
-
Quality loss converting Pro Res to mp4
Hi I have a problem with the workflow from After Effects to a final .mp4 video. I have been editing time lapses in After Effects, and exporting them as Pro Res HQ- all good so far. However, I can´t seems to be able to convert the Pro Res file to a .m