Parsing, Modifying, and outputting XML Documents with Java

java

I have been doing a lot of XML parsing, and manipulation in java lately because I'm building a super dynamic configuration editor for XMS. Its going to be pretty cool once its done because you can even configure third party modules with it. Anyways I thought I'd post some a simple example of parsing and modifying XML with java:

Suppose you have the following XML document:

<?xml version="1.0" ?>
<earth>
    <country>us</country>
</earth>

First to parse it using a DOM parser, you can use the DocumentBuilderFactory to get the default DOM parser for your JVM:

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("/path/to/file.xml");

Now you have an object representation of the XML file in a DOM Document object.

Adding an attribute

Suppose you wanted to add an attribute to the earth node:

Node earth = doc.getFirstChild();
NamedNodeMap earthAttributes = earth.getAttributes();
Attr galaxy = doc.createAttribute("galaxy");
galaxy.setValue("milky way");
earthAttributes.setNamedItem(galaxy);

Adding a child tag

Now lets suppose you wanted to add a child node:

Node canada = doc.createElement("country");
canada.setTextContent("ca");
earth.appendChild(canada);

Write the XML document to a string or file

Finally you probably want to write the xml document to a string or to a file, this can be done with a Transformer object, which come from the transformer factory:

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);

String xmlString = result.getWriter().toString();
System.out.println(xmlString);


269 people found this page useful, what do you think?

Trackbacks

Trackback Address: 445/DB6030F47DA07A9E7532444CD00ED2C0

Comments

On 09/27/2005 at 11:12:49 AM UTC Emine wrote:
1
Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes");

//initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); trans.transform(source, result);

String xmlString = result.getWriter().toString(); System.out.println(xmlString);

Hi i dont understand what is trans in trans.transform(source, result);

On 09/27/2005 at 11:14:27 AM UTC Pete Freitag wrote:
2
that should be transformer.transform() I will update

On 12/12/2005 at 10:37:59 PM UTC sally wrote:
3
Thank you..your explenation is perfect

On 01/09/2006 at 4:26:41 AM UTC Sweetypie wrote:
4
I'm new to xml as well as java. And this piece of code did help a lot. But, I wanted to know that when I tried to add a new child node, it was added & the entire xml file was displayed on the console, but my original xml file remained unaltered. How can I add the new nodes to the original xml file? Also, I am validating the xml file against a schema, so while adding new child nodes, will the validation happen automatically against the schema or do i have to write some code for that as well. Please help!!!

On 03/13/2006 at 2:19:46 AM UTC Chung Lam wrote:
5
i am having the same problem as the person above, i need to update the actual xml file. Please help!

On 03/26/2006 at 4:10:24 AM UTC John wrote:
6
To modify an XML file already in existance, you'll want to read the file into a buffer, (modifying the particular attribute while doing so), and then print the entire buffer back to the file.

On 04/07/2006 at 11:13:12 PM UTC satish wrote:
7
thanks for the explanation...helped a lot

On 06/12/2006 at 4:06:24 AM UTC suvarna wrote:
8
Good piece of code...working & yes with a line modification you can write the changes to the same file

On 07/04/2006 at 10:48:37 AM UTC Paolo wrote:
9
Does this code require some "extra libraries" installed? I'm getting a cannot resolve symbol error and I can't understand why. I'm running java version "1.4.2_05".

Ah, forgot to mention that I'm a newbie and this is my first coding experiment with Java, so excuse me if the question sounds silly.

Thanks.

On 07/13/2006 at 8:48:58 AM UTC Sweeti wrote:
10
Can any one tell how to format a xml file through java program.

On 07/13/2006 at 8:53:24 AM UTC Anonymous wrote:
11
I want to create a new xml file .How can I create it through java progrm. How can I add tags/element, adding attributes etc into it . Plz help ...its very urgent . Thanks a lot in advance !!!!

On 07/13/2006 at 8:53:50 AM UTC Pooja wrote:
12
I want to create a new xml file .How can I create it through java progrm. How can I add tags/element, adding attributes etc into it . Plz help ...its very urgent . Thanks a lot in advance !!!!

On 07/21/2006 at 5:44:04 PM UTC Vijay wrote:
13
Hi,

Is there way to modify XML file using JAXP, I am able to overwrite the file with the changes need, but would like to have the same file modified(one particular tag) than completely overwriting the XML file.

Thanks , Vijay

On 08/23/2006 at 4:32:44 AM UTC Shashi wrote:
14
I want to read data from a xml file and want to put the data into a table of postgresql database using core Java .Please help me in coding it.

On 09/27/2006 at 5:08:52 AM UTC Kishore wrote:
15
Hi, Your code is very good. But I need some more clarity for adding another node with same node name. You specified some code in this site but it is not adding correctly under the specified node. It is getting added as new node without parent node and I need to get the XML file updated as I add some nodes or attributes in the program. Please help me in this regard.

Thanks Kishore

On 10/18/2006 at 1:18:22 PM UTC Vikas wrote:
16
Is there any way I can use a string "/0" as node name in xml ? when I try to use it the xml parser treats "/" as file separator and my node is not there.

On 12/01/2006 at 5:09:49 AM UTC Deepak wrote:
17
Good Article. Accept my appreciation .

On 12/08/2006 at 12:12:42 AM UTC Jiju Jacob wrote:
18
Very Good One. Helped me a lot. Thanks.

On 01/12/2007 at 6:15:43 AM UTC Dennis Parrott wrote:
19
Great code! It helped me a lot. I was amazed that the DOM API does not provide this facility out of the box. Also it would be nice if it was possible for updates to the DOM were reflected in the input file automatically. Do you know if this is possible with later versions of the DOM API?

On 01/29/2007 at 5:55:56 AM UTC Rishi wrote:
20
Hi, transformer.setOutputProperty(OutputKeys.INDENT, "yes"); The above line sets the indentation true and every new tag starts in a new line Is there any way that I can selectively indent my XML on a certain tag and not on the other.

On 01/30/2007 at 6:53:03 AM UTC Edwin HincapiƩ wrote:
21
Excellent article, took me out of difficulties, thank you.

On 03/28/2007 at 2:18:58 PM UTC Jason wrote:
22
The above code is EXACTLY how I've been mutating xml files in Java code, but there's a snag.

When you set the indent output property of a transformer to true, and write the xml file, it inserts text nodes to facilitate the new-lines and tabs. Then when you parse, it reads these new-lines and tabs as text nodes. Then if i remove a node that is between two other nodes, and re-write the xml file, the surrounding text nodes are concatenated and we see a big break.

Thusly:

Original xml:

<HeadTag> <Stuff>"First"</Stuff> <Stuff>"Second"</Stuff> <Stuff>"Third"</Stuff> </HeadTag>

then if I parse and remove the Element with name "Stuff" and text content "Second" and then re-write, I see:

<HeadTag> <Stuff>"First"</Stuff> <Stuff>"Third"</Stuff> </HeadTag>

I have confirmed this is what is happening by obtaining a NodeList of all the children of the documentElement and traversing the list printing the node type name and value for each.

Any suggestions?

~Jason

On 03/28/2007 at 2:24:34 PM UTC Jason wrote:
23
Shoot... I just read my post and the example xml that I wrote came out improperly formatted. Let me rewrite just the xml.

Original:

<HeadTag><p> <br><br><Stuff>"First"</Stuff><p> <br><br><Stuff>"Second"</Stuff><p> <br><br><Stuff>"Third"</Stuff><p> </HeadTag>

After deleting 'Stuff' element with "Second": <HeadTag><p> <br><br><Stuff>"First"</Stuff><p> <p> <br><br><Stuff>"Third"</Stuff><p> </HeadTag>

On 03/29/2007 at 6:04:47 AM UTC Ben wrote:
24
when I use "DocumentBuilderFactory to get the default DOM parser for your JVM" I get to the XML file - the parse method returns [#document : null] what is the reason ?

On 03/29/2007 at 7:21:27 AM UTC Chris wrote:
25
Thanks Pete! I was looking for a quick code example on how to output my modified DOM to a file. This was exactly what I needed. Cheers!

On 04/19/2007 at 8:05:26 AM UTC syed muqthadir wrote:
26
Here i had used Dom parser to read an Xml file.Is it that we can update element content or value trough java program. For example: <fontsize>12</fontsize> so here 12 value should change it to 14,16 like that in xml file trough java program.

Right then if any updates plz send it to my Email id muqthadir_ali@yahoo.co.in

On 07/03/2007 at 3:33:22 AM UTC sharan wrote:
27
<element name="details"> <element name="server"> <model>G2</model> <serial-number>053232a</serial-number> <rom-version>sdfsd, Type 01212</rom-version> </element>

<element name="os"> <type>linux</type> <version>4.0</version> </element> </element>

How do i remove the Element with the name "element" and replace it with the attribute value.

Help me in this regards....

On 07/03/2007 at 4:04:18 AM UTC sharan wrote:
28
<element name="details"> <element name="server"> <model>G2</model> <serial-number>053232a</serial-number> <rom-version>sdfsd, Type 01212</rom-version> </element> <element name="os"> <type>linux</type> <version>4.0</version> </element> </element>

How do i remove the Element with the name "element" and replace it with the attribute value.

if you have a small example for this ...please provide me

On 07/03/2007 at 8:49:26 AM UTC Mocx wrote:
29
hi, i have found the above script useful, however i want to generate reports from xml files. i want to read specific nodes in xml file and output them to xsl file or any txt file. any ideas on how to go about this? im new to xml parsing but i have worked with java in university so im still novice to the professional world.

On 07/05/2007 at 4:04:50 AM UTC Amod wrote:
30
Thankx for the help....it worked for me :)

On 07/09/2007 at 12:22:22 AM UTC haritha wrote:
31
hai ur explanation is nice.it helps everyone to solve problems while creatinfg xml thanks.

On 08/08/2007 at 6:53:26 AM UTC ajay wrote:
32
Hi, please tell me how to sort this xml file, if i m updating it on runtime.

On 08/21/2007 at 12:12:20 AM UTC venkat wrote:
33
i want to add particular attribute into the paticular coloumn

On 08/29/2007 at 3:51:19 AM UTC tirumala wrote:
34
hi all, i want to add a new node for under a pariticular node .is the any possibity of adding it through Dom paser?.or i need to go for jdom?

regards tirumala

On 09/18/2007 at 3:34:11 AM UTC rekhchand malpani wrote:
35
Hi, i want to read (separate) the attributes of xml file without using tagname in java. please help me. Thanks.

On 10/03/2007 at 5:49:34 AM UTC Anonymous wrote:
36
Hi,

Does this code handles reading very large XML files.. say around 1 GB in size? How to read those files? Thanks

On 10/10/2007 at 3:20:57 PM UTC ghgj wrote:
37
http://www.forex.co.ir http://www.meta-fx.com forex ?????

On 10/26/2007 at 2:14:59 AM UTC Sankar wrote:
38
Hi, its very useful to me. I tried to update the xml, last two days but now I did it within a moment. Thanks for your kind help.

On 11/12/2007 at 8:45:35 AM UTC Malcovitch wrote:
39
Hi,

I also get [#document : null] when using DocumentBuilderFactory... does anyone have a reason/solution for this?

On 12/03/2007 at 10:38:01 AM UTC stratoz wrote:
40
thx for the help buddy... urz is the first link wen ne1 doez a google search fr thz query.... gr8 work... thxx :)

On 12/03/2007 at 3:55:59 PM UTC anil wrote:
41
I have xml file in absolute path and I am not able to get the output stream to this file.. can any one give some thoughts on this.

On 12/17/2007 at 10:28:30 PM UTC Rajiv wrote:
42
How can I add element in such a manner. <?xml version="1.0" ?> <Global> <earth> <country>us</country> </earth>

On 12/17/2007 at 10:31:05 PM UTC Rajiv wrote:
43
Sorry! It will be <?xml version="1.0" ?> <Global><earth> <country>us</country> </earth></Global>

On 01/17/2008 at 11:35:43 AM UTC bhanu wrote:
44
hi all, i have prob in inserting data into xml file,retrieving data from xml file,deleting data from xml file,updation of data in xml file through java(jdom). pls help me for my project

On 01/22/2008 at 11:28:58 PM UTC Ganesh wrote:
45
Hi, I am new to xml can anyone send which site and material is good. Thanks alot for advance

On 01/29/2008 at 11:55:41 PM UTC prasanna wrote:
46
Hi I want small info, how to modify the data available in the xml file can any body help me which is very important for my project.

On 02/11/2008 at 12:23:02 AM UTC ravi wrote:
47
the Indentaion works in windows but somehow is not working in linux... where cud i have possiblely gone wrong... plz help...

On 02/11/2008 at 4:32:21 AM UTC biswa wrote:
48
Here i had used Dom parser to read an Xml file.Is it that we can update element content or value trough java program. For example: <fontsize>12</fontsize> so here 12 value should change it to 14,16 like that in xml file trough java program. Right then if any updates plz send it to my Email id biswa.nilu@gmail.com

On 02/15/2008 at 4:47:33 AM UTC Anonymous wrote:
49
thnx for the explaination.. but i have a doubt,instead of using DocumentBuilderFactory,if i use DOMParser parser=new DOMParser(); and tried to parse the xml file, im not getting the output.. i do the pgms in IBM Eclipse, is it prblm with eclipse or the pgm

please let me know..

On 02/15/2008 at 4:50:23 AM UTC Anonymous wrote:
50
thnx for the explaination.. but i have a doubt,instead of using DocumentBuilderFactory,if i use DOMParser parser=new DOMParser(); and tried to parse the xml file, im not getting the output.. i do the pgms in IBM Eclipse, is it prblm with eclipse or the pgm please let me know..

here is the pgm:

import org.w3c.dom.*; import org.apache.xerces.parsers.DOMParser; import java.io.*; //import javax.xml.parsers.DocumentBuilder; //import javax.xml.parsers.DocumentBuilderFactory;

public class CountNodes { public static void main(String[] args) { try{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter file name: "); String str = bf.readLine(); File file = new File(str); if (file.exists()){ DOMParser parser = new DOMParser(); parser.parse(str); Document doc = parser.getDocument(); /* DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file);*/ System.out.print("Enter element that have to count: "); String ele = bf.readLine(); NodeList list = doc.getElementsByTagName(ele); System.out.println("Number of nodes: " + list.getLength()); } else{ System.out.println("File not found!"); } } catch (Exception e){ e.getMessage(); } } }

On 02/15/2008 at 4:50:33 AM UTC Anonymous wrote:
51
thnx for the explaination.. but i have a doubt,instead of using DocumentBuilderFactory,if i use DOMParser parser=new DOMParser(); and tried to parse the xml file, im not getting the output.. i do the pgms in IBM Eclipse, is it prblm with eclipse or the pgm please let me know..

here is the pgm:

import org.w3c.dom.*; import org.apache.xerces.parsers.DOMParser; import java.io.*; //import javax.xml.parsers.DocumentBuilder; //import javax.xml.parsers.DocumentBuilderFactory;

public class CountNodes { public static void main(String[] args) { try{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter file name: "); String str = bf.readLine(); File file = new File(str); if (file.exists()){ DOMParser parser = new DOMParser(); parser.parse(str); Document doc = parser.getDocument(); /* DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file);*/ System.out.print("Enter element that have to count: "); String ele = bf.readLine(); NodeList list = doc.getElementsByTagName(ele); System.out.println("Number of nodes: " + list.getLength()); } else{ System.out.println("File not found!"); } } catch (Exception e){ e.getMessage(); } } }

On 03/27/2008 at 3:45:38 PM UTC Jessica wrote:
52
hi I have wirte xml file using java code but now I want to add or edit data on it like I entered record 1 I want now to stop at record tag then add a new record 2 how may I do that thanks in advance <record>1</record>

On 05/30/2008 at 7:35:18 AM UTC Oni wrote:
53
Hi I would use the transformer to write an XML File. <?xml version="1.0" encoding="UTF-8"?> <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"> <wsp:All> <wsp:ExactlyOne> <wsp:All> <prefix:localNamxmlns:prefix="namespaceURI"/> </wsp:Policy> but the indent doesn't work. could somebody help me?

On 06/01/2008 at 1:58:59 PM UTC Ms.Ranjan wrote:
54
This is a great link it really helped me a lot...thanks.. the code which i pasted below is for the beginners and for those who got [#document : null] in the ouput file,even i got the same problem..below is the solution..

thanks for the author of this link..great work.. import javax.xml.parsers.*; import org.w3c.dom.*; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamResult; import java.io.*;

public class ODOM { public static void main(String args[]) throws Exception {

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse("earth.xml");

Node earth = doc.getFirstChild(); NamedNodeMap earthAttributes = earth.getAttributes(); Attr galaxy = doc.createAttribute("galaxy"); galaxy.setValue("milky way"); earthAttributes.setNamedItem(galaxy);

Node canada = doc.createElement("country"); canada.setTextContent("ca"); earth.appendChild(canada);

Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes");

//initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, new StreamResult(new

FileOutputStream("copyearth.xml")));

On 07/17/2008 at 4:07:08 AM UTC Girish Tewari wrote:
55
thanks for giving the idea of using transformerfactory.

On 10/22/2008 at 1:17:27 AM UTC Rajneesh wrote:
56
very good, but how could i modify value of existing node

On 10/23/2008 at 5:25:38 AM UTC Andy wrote:
57
Thanks - very concise and a great help. Saved me a few hours!

On 11/26/2008 at 6:06:53 PM UTC ranjan wrote:
58
Hi, I am using XMLSpreadsheet and after updating the values, I am not able to open it. But can see in editplus. It seems of formating issues. any help plz....

On 12/18/2008 at 8:27:12 AM UTC anon wrote:
59
hi, i want a piece of code that would read data froma database(MySql) and convert it into Xml file. plz help!!!

On 01/29/2009 at 5:09:07 AM UTC Naveen wrote:
60
Hi,

How can i modify a particular tag in an XML document using DOM.

i am a newbie can any one please help me with this.

On 02/02/2009 at 12:11:33 PM UTC Naveen wrote:
61
Hi suvarna,

can you please let me know how can we modify the value of a particular tag in a XML document. how can it be written in the same XML document.

can you please help me with this by giving a sample code...

That would be of a great help to me ..

Thanks

On 03/16/2009 at 2:11:48 AM UTC madhavi wrote:
62
can you please let me know how can we modify the value of a particular attribute in a XML document.

On 03/16/2009 at 2:12:40 AM UTC madhavi wrote:
63
can you please let me know how can we modify the value of a particular attribute in a XML document.

On 03/16/2009 at 2:14:11 AM UTC madhavi wrote:
64
can you please let me know how can we modify the value of a particular attribute in a XML document. Thanks in advance. That would be of a great help to me ..

On 04/08/2009 at 8:53:53 AM UTC Vishnu wrote:
65
For all the guys who want to update a particular field in the xml file .... use the following API to test.. u can modify it as required.First get the document by parsing it.

NodeList sections = document.getElementsByTagName("sect1"); int numSections = sections.getLength(); for (int i = 0; i < numSections; i++) { Element section = (Element) sections.item(i); // A <sect1>

Node title = section.getFirstChild(); while (title != null && title.getNodeType() != Node.ELEMENT_NODE) title = title.getNextSibling();

if (title != null) System.out.println(title.getFirstChild().getNodeValue()); }

On 05/26/2009 at 11:26:02 PM UTC Krishnan wrote:
66
Below is the Example of creating XML file using Java and simple understanding of root and element

import java.io.StringWriter;

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;

public class vsktestXML { public vsktestXML() { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); // Setting the ROOT Element results = doc.createElement("KOKO"); doc.appendChild(results); //Setting the First ELEMENT Element row = doc.createElement("ITDEPT"); results.appendChild(row); //Setting the CHILD 1 String columnName = "SERVER"; String val = "VSKSERVER"; Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(val)); row.appendChild(node); //Setting the CHILD 2 String columnName2 = "PC"; String val2 = "VSKPC"; Element node1 = doc.createElement(columnName2); node1.appendChild(doc.createTextNode(val2)); row.appendChild(node1); //Setting the CHILD 3 String columnName3 = "NETWORK"; String val3 = "VSKLAN"; Element node2 = doc.createElement(columnName3); node2.appendChild(doc.createTextNode(val3)); row.appendChild(node2);

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, "ISO-8859-1"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); StreamResult sr = new StreamResult(sw); transformer.transform(domSource, sr); System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?> " ); System.out.println(sw.toString()); } catch (Exception e) { e.printStackTrace(System.out); }

} }

On 05/27/2009 at 2:29:57 AM UTC Krishnan wrote:
67
XML File for the above sample

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Personnel> <Employee type="permanent"> <Name>KRISHNAN</Name> <Id>1005</Id> <Age>37</Age> </Employee> </Personnel>

On 05/27/2009 at 2:30:46 AM UTC Anonymous wrote:
68
The above example is by krishnan@vigshakri.com

On 05/27/2009 at 2:32:29 AM UTC Krishnan wrote:
69
By www_vigshakri_com

On 08/04/2009 at 10:58:15 AM UTC Parvez Ahmad Hakim wrote:
70
Really nice code. Above code actually converts xmltext of document to string

On 08/04/2009 at 7:25:19 PM UTC Raj wrote:
71
I was using 1.4.x jre to generate XML file, when I use 1.5.x to generate XML file with same code. I am getting additional xmlns="" for the newly added xml element. what is the possible reason and how to avoid this? if i use 1.4.x i dont see the xmlns ="" for the newly added xml element. Any suggestions/solution please.

On 08/21/2009 at 1:04:23 PM UTC anon_anon wrote:
72
VTD-XML allows you to modify XML documents incrementally...

On 09/22/2009 at 7:56:00 AM UTC Srivinayaka P wrote:
73
Hell everyone,

I have a problem. This might be out of the current context. Any ways, can anyone please tell me how to modify the namespace attribute of an already loaded DOM object?

On 10/13/2009 at 8:31:18 AM UTC Surendar wrote:
74
Can I get complete set of code for Parsing, Modifying, and outputting XML Documents with Java this program???

On 10/13/2009 at 8:37:33 AM UTC Surendar wrote:
75
I need the code for the following set of XML file:

<?xml version="1.0" encoding="UTF-8" ?> - <Personnel> - <Employee type="Permanent"> <Name>Seagull</Name> <Id>3674</Id> <Age>34</Age> </Employee> - <Employee type="Contract"> <Name>Robin</Name> <Id>3675</Id> <Age>25</Age> </Employee> - <Employee type="Permanent"> <Name>Crow</Name> <Id>3676</Id> <Age>28</Age> </Employee> <Employee Type="Contract" /> </Personnel>

On 10/20/2009 at 10:18:01 AM UTC kkrizin wrote:
76
the remove xml declaration works in windows but it's not working in linux... is there any way to get this to work?

On 11/04/2009 at 11:20:33 PM UTC Anonymous wrote:
77
how will we give the path of our xmal file for this line if we are getting this xml file while runtime and we are storing it into a variable.

Document doc = docBuilder.parse("/path/to/file.xml");

On 11/17/2009 at 11:51:56 PM UTC barriers wrote:
78
You may want to look at vtd-xml, the latest open source xml parsing/xpath/indexing lib

http://vtd-xml.sf.net

On 12/02/2009 at 6:51:08 AM UTC moe wrote:
79
Hello,

How to add to an xml document instead of over writing it:

Any help will be much appreciated...thanks in advance.

I have managed to get my code to write an xml file with data from input fields from a jsp page... Now I actually need to add new entered details on the jsp page to the existing xml file instead of rewriting it everytime My sample code which currently rewrite the xml file is as follow bellow:

public void addContact(String name, String number) {

System.out.println("New Contact's Name and Number are '" + name + "' and '" + number + "' respectively.!!!");

//to write...Xml writer code

System.out.println("got here start of write Xml***");

//this method gets called but only rewrites the Xml file //Really need it to append/add to the Xml file

try { String filename = getClass().getClassLoader().getResource("contact-db.xml").getPath(); FileOutputStream fos = new FileOutputStream(filename); fos.write("<?xml version = \"1.0\"?>".getBytes()); String s = "";

s += "<contacts>"; s += "<contact>"; s += "<name>"; s += name; s += "</name>"; s += "<number>"; s += number; s += "</number>"; s += "</contact>"; s += "</contacts>";

s += "";

fos.write(s.getBytes("utf-8")); fos.close();

//check to see this method got called or not?

System.out.println("***got here end of write Xml");

} catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }

}

On 02/19/2010 at 7:38:07 AM UTC sudha wrote:
80
nice code it really helped me

On 02/26/2010 at 5:28:43 AM UTC Mayur wrote:
81
Hi, I need to create new xml files from existing by changing node values. Can you help me how can i do it.

Thanks in Advance, Mayur

On 03/13/2010 at 11:26:11 AM UTC Nada wrote:
82
Great help it works for me. Thnx

On 03/14/2010 at 7:39:15 AM UTC siddharth wrote:
83
I need the code for the following set of XML file:

<?xml version="1.0" encoding="UTF-8" ?> - <Personnel> - <Employee type="Permanent"> <Name>Seagull</Name> <Id>3674</Id> <Age>34</Age> </Employee> - <Employee type="Contract"> <Name>Robin</Name> <Id>3675</Id> <Age>25</Age> </Employee> - <Employee type="Permanent"> <Name>Crow</Name> <Id>3676</Id> <Age>28</Age> </Employee> <Employee Type="Contract" /> </Personnel>

plz send it to siddharthareddy4u@gmail.com its urgent

On 03/14/2010 at 7:42:24 AM UTC siddhartha wrote:
84
i need the code 2 read attibute values inside a tag. like <measValue measObjLdn="BSS:0,BTSM:3,BTS:0"> <measResults>0 0 </measResults> <suspect>true</suspect> </measValue> i need a java code to read measObjLdn help me if u can

On 03/16/2010 at 6:02:52 AM UTC kevin wrote:
85
this is a tutorial that show you how to develop a simple java class that use CRUD (Create Read Update Delete) operations with an xml file stored in a native XML Database: http://www.scribd.com/doc/28280460

On 03/17/2010 at 9:40:13 PM UTC siddharth wrote:
86
thanks Kevin, do u have any idea about csv(comma seprated values) file format. if plz let me know.

On 03/22/2010 at 2:48:35 AM UTC Hitesh Patel wrote:
87
hello sir, i am infant for java and working in advance java. i have a quarry about .java file whose addressed is when tagged in xml file then it is non-supportive for my file. i just wanna know whether i am going in right direction or wrong. my xml code is :- <?xml version="1.0" encoding="ISO-8859-1"?> <web-app> <servlet> <servlet-name>index</servlet-name> <servlet-class>hitesh.index</servlet-class> </servlet> <servlet-mapping> <servlet-name>index</servlet-name> <url-pattern> /index</url-pattern> </servlet-mapping> <servlet> <servlet-name>LogIn</servlet-name> <servlet-class>hitesh.LogIn</servlet-class> </servlet> <servlet-mapping> <servlet-name>LogIn</servlet-name> <url-pattern> /LogIn</url-pattern> </servlet-mapping> <servlet> <servlet-name>homepage</servlet-name> <servlet-class>hitesh.homepage</servlet-class> </servlet> <servlet-mapping> <servlet-name>homepage</servlet-name> <url-pattern> /homepage</url-pattern> </servlet-mapping> <servlet> <servlet-name>valid</servlet-name> <servlet-class>hitesh.valid</servlet-class> </servlet> <servlet-mapping> <servlet-name>valid</servlet-name> <url-pattern> /valid</url-pattern> </servlet-mapping> <servlet> <servlet-name>registration</servlet-name> <servlet-class>hitesh.registration</servlet-class> </servlet> <servlet-mapping> <servlet-name>registration</servlet-name> <url-pattern> /registration</url-pattern> </servlet-mapping> ---------------------- <servlet> <servlet-name>reg</servlet-name> <servlet-class>hitesh.reg</servlet-class> </servlet> <servlet-mapping> <servlet-name>reg</servlet-name> <url-pattern> /reg</url-pattern> </servlet-mapping> ------------------------ <servlet> <servlet-name>regsucc</servlet-name> <servlet-class>hitesh.regsucc</servlet-class> </servlet> <servlet-mapping> <servlet-name>regsucc</servlet-name> <url-pattern> /regsucc</url-pattern> </servlet-mapping> </web-app> The code which is separated by(---)is the only .java file. Dose it correct ?

On 03/26/2010 at 10:31:59 AM UTC Said wrote:
88
Hi folks,

i heard about vtd-xml and trying to use it in a project. does somebody here know how to get the result of an xpath evaluation in a string. for example:

<R> <A> <B id = "1">a text</B> <C>another text</C> </A> <A> <B id = "2">a text</B> <C>another text</C> </A> </R>

the xpath query = "/R/A";

and I would like to get the structure <A> <B id = "1">a text</B> <C>another text</C> </A> <A> <B id = "2">a text</B> <C>another text</C> </A>

is it possible with vtd-xml?

Thank you

On 05/26/2010 at 4:21:34 AM UTC ashutosh gangrade khalwa wrote:
89
sir i m working on xml database and i want to edit it time to time but i m facing a problem when i edit this database.

On 05/28/2010 at 6:43:31 AM UTC bharat kashyap wrote:
90
sir,i need your help in providing interface for reading and writing the xml content in jsp....

On 08/02/2010 at 5:02:53 PM UTC WP Themes wrote:
91
Amiable post and this post helped me alot in my college assignement. Say thank you you as your information.

On 09/10/2010 at 7:49:35 AM UTC angelthomos wrote:
92
hi, thank for you...your providing this Good Article.nice code it really helped me. __________________________ angelthomos

On 09/10/2010 at 7:54:18 AM UTC angelthomos wrote:
93
thank for you.. providing this code is very helpme.

On 09/21/2010 at 8:57:16 AM UTC Manas wrote:
94
Hey,

Can I read some value from my external file (Text etc) in my XML File?

On 09/24/2010 at 10:59:55 AM UTC jordan wrote:
95
I have created a xml file using jdom and i want to remove the encoding parameter . How to do that? My output <?xml version="1.0" encoding="UTF-8"?> My desired output <?xml version="1.0"?>

On 09/24/2010 at 4:13:07 PM UTC jordan wrote:
96
"I have created a xml file using jdom and i want to remove the encoding parameter . How to do that? My output <?xml version="1.0" encoding="UTF-8"?> My desired output <?xml version="1.0"?> "

(Format.getPrettyFormat().setOmitEncoding(true))

On 09/29/2010 at 8:41:30 AM UTC Supratim wrote:
97
how do i marshall java classes to xml documents without declaring the object name?

On 12/13/2010 at 4:57:43 AM UTC Pradeep Nandi wrote:
98
Hi All, I have some problem to parse whole XML file. when i am parsing the xml file, once it is getting only one error the xml document then it is terminating, but i need parse should all the error in xml file and at the end should return all the list of errors.

Thank you in advance..

On 12/13/2010 at 5:09:56 AM UTC Pradeep Nandi wrote:
99
Hi All, I have some problem to parse whole XML file. When i am parsing the xml file, once parser is getting one error in xml document then it is terminating, but i need parse should continue and collect all the errors in xml file and at the end should return all the list of errors. Thank you in advance..

On 12/27/2010 at 4:00:36 AM UTC Prasanna Kumar wrote:
100
Hi, The Way you made the Steps to Explain is Excellent which makes To Understand at all level of programmers. Thank you

On 01/13/2011 at 1:15:46 AM UTC Anonymous wrote:
101
xml' already exists in this location. do u want to replace it?

On 02/03/2011 at 4:08:32 AM UTC Aman Verma wrote:
102
Thanks for such an informative post. I hope I did not miss any comment in this thread, so adding following code for generating XML instead of getting result as String:

StreamResult result = new StreamResult("X:\\Path\\of\\File.xml");

It will directly write to this file location.

Secondly, In case you are Marshalling the java to xml through Jaxb, then you can directly make an InputSource object and parse it with DOM code as mentioned in initial post above:

StringWriter strWritObj = new StringWriter(); InputSource inptSrcObj = new InputSource(); marshaller.marshal(Object , strWritObj );

inptSrcObj.setCharacterStream(new StringReader(strWritObj .toString()));

Now parse this inputSource object :

Document doc = docBuilder.parse(inptSrcObj);

Let me know in case you need more information. Or please let me know in case there is a better way to edit an xml produced by JAXB.

On 02/19/2011 at 11:55:20 AM UTC NAManuel wrote:
103
Will the north star (polaris) always be the north star?

On 02/21/2011 at 6:22:46 AM UTC XHPreston wrote:
104
okay so my red blackberry curve is pulverized so im getting a new fone..i get at&t i cannot dissipate more than $360 and im not starting a novel plan. I was looking at the older Treo's. Is there any phone you recommend? I abstract a heaps so i need proof battery. Also what is your reconsideration on the phone. and if you comprise the older treo do u like it? what r the pro's and cons? take!

On 02/23/2011 at 6:32:18 AM UTC CarlosLS wrote:
105
I principled present up on some rousing new electric cars that inclination be coming out in the next 3 years that affiliation my budget and inclination from up to 300 mpg!!! But I was wondering, how these cars would touch on a row after a ice storm? The buggy would be great through despite me, but i active in the midwest and need a buggy that can have about ice and snow. The information I would like to have is the ordinary power an electric car, front/rear in drive, and favoured space.

On 03/06/2011 at 3:58:38 PM UTC Twepeunap wrote:
106
Why do we change foriegn place names to other than the real name? Example being Munchen or Munich?

On 03/08/2011 at 5:59:24 AM UTC elassytaime wrote:
107
What's the disagreement between Burnout Paradise and the Maximum Thump edition? I want to get burnout paradise recompense xbox 360 but I set up faulty that there is an ultimate box edition also. I can get either of them fetching tatty but I don't positive which equal to get.

On 04/06/2011 at 3:52:35 PM UTC masters tournament wrote:
108
im a 19 years old student , i weigh 102 pounds and 5.4 ,, im on 1650 calories which is the calories i need to maintain my weight ,but i started eating 1600 to 1650 and still feel kinda tired , and im doing it by eating only indomie , or instant noodles each back has 350 , and i think they have no vitamins , so whats a better way to eat but still eat 1650 calories ,not more

On 04/25/2011 at 2:16:26 AM UTC Anonymous wrote:
109
i need sample example to append multiple child nodes to the parent nodes in xml file

On 05/04/2011 at 1:56:57 AM UTC Muhammad Ali Hassan wrote:
110
Hi Pete Freitag, Your article about xml with java is perfect and I am not able to pay you thank for your effort.

On 08/30/2011 at 7:30:54 AM UTC Aarti wrote:
111
hi my xml contains arabic characters but still not displaying on pdf below is my xml generated by java

<?xml version="1.0" encoding="UTF-8"?><VehicleSaleInvoice><Header><Title>CAR SALE INVOICE</Title><CompanyName>DALEEL</CompanyName><Address>, 0 </Address><Invoice>2000000026</Invoice><PostalNo> </PostalNo><City>. , </City><Country/><InvoiceDate>30/08/2011</InvoiceDate><PhoneNo> </PhoneNo><FaxNo> </FaxNo><VatNo> </VatNo><Email> </Email><AccountNo/></Header><BillingInformation><Name>TEST</Name><DebitorNo>10001</DebitorNo><Address/><VatNumber> </VatNumber><PostalNo/><Country>Algeria </Country></BillingInformation><VehicleInformation><Make>mercedez </Make><VehicleNoAndUnit>777 0020030005</VehicleNoAndUnit><Model>????? ???? ????? 2011</Model><ModelYear>0</ModelYear><VehicleKms>700</VehicleKms><ChasisNo> </ChasisNo><ProductionDate/><EngineNo> </EngineNo><Color> </Color></VehicleInformation><Details><Item>Car Sale</Item><Quantity>1</Quantity><AmountPerQuantity>143148.00</AmountPerQuantity><NetAmount>143148.00</NetAmount><ServicePer>0.00</ServicePer><ServiceAmount> 0.00</ServiceAmount><VATPer>0.00</VATPer><VATAmount> 0.00</VATAmount><TotaAmount>143148.00</TotaAmount></Details><Footer><EmployeeName>S Supervisor</EmployeeName></Footer></VehicleSaleInvoice>

i have to display model in arabic on my pdf i have set encoding proprty to utf-8 still no luck

On 09/07/2011 at 4:47:08 AM UTC Sanjeev wrote:
112
I am trying to update an existing XML file with the below content. <Company> <Region> <Employee> <Name> Harish </Name> <Age> 26 </Age> </Employee> </Region> </Company>

After updating the content should look like

<Company> <Region> <Employee> <Name> Harish </Name> <Age> 26 </Age> </Employee> <Employee> <Name> Vinod </Name> <Age> 29 </Age> </Employee> </Region> </Company>

How can this be done programatically through Java using DOM API's.

On 09/16/2011 at 2:58:23 AM UTC Usha wrote:
113
I Need to read a pdf from URL and parse it to XML using java. can anyone help to do this process.

On 11/02/2011 at 9:21:39 AM UTC pria wrote:
114
Is it possible to write multiple DOm objects to a single Xml file? To make it more clear, i have multiple sources and only one result. transformer.transform(source, result); How do i use transfor object and get this done?

On 12/03/2011 at 1:23:00 PM UTC sbasu wrote:
115
how can i save the newly modified xml document into another xml document

On 12/30/2011 at 4:19:25 PM UTC Jim Pratt wrote:
116
Here is an example method that writes the Xml doc object to a file and to the screen: public static void writeXmlFile(Document doc, String filename) { try { // Prepare the DOM document for writing Source source = new DOMSource(doc);

// Prepare the output file File file = new File(filename); Result result = new StreamResult(file); Result outResult = new StreamResult(System.out);

// Write the DOM document to the file Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); xformer.transform(source, result); xformer.transform(source, outResult); } catch (TransformerConfigurationException e) { } catch (TransformerException e) { } }

On 05/07/2012 at 5:22:43 AM UTC vinod wrote:
117
please how to insert the data into xml floder its urgent

On 06/01/2012 at 1:10:49 PM UTC hanan wrote:
118
sample java code to dd data to xml file from java program

On 08/12/2012 at 12:24:12 PM UTC venkateshrao wrote:
119
0 down vote favorite

I have a xml file like below

<documents> <document> <document_type>I</document_type> <acct_number>A1093879600</acct_number> </document> <document> <document_type>I</document_type> <acct_number>A0350070800</acct_number> </document>

First of all I have to check <document_type> value If the value equals I or G then I need to read <acct_number> value from XML then I need to connect with database and pull up the baseid associated with that <acct_number> and write that baseid to xml after <acct_number> node.

Any help appreciated...

Thanks in advance....

On 08/13/2012 at 2:50:49 AM UTC Aman wrote:
120
Best you use JaxB. Create an XML Schema for your XML(tools available on internet) then create JaxB classes from the schema can be done via "Trang". Then you can unmarshal your XML to java, get account Id, query db , populate baseid object and then marshal your object back to XML

On 09/20/2012 at 11:43:15 AM UTC Anonymous wrote:
121
i have got error here Document doc = docBuilder.parse("/path/to/file.xml");

cant find symbol

On 10/22/2012 at 6:43:45 AM UTC dorothy wrote:
122
This is a useful article, but can anyone advise that if the updates to the physical file have to be done by parallel running threads, then show can the integrity of the structure of xml be ensured? Since in the given example, only one thread is updating the file, so things are ok, but in case of multi threaded app what can be done?

On 09/09/2014 at 2:31:20 AM UTC lolzzzzz wrote:
123
ks kn ihd fx ghg iuls gf duh gziu fg sfgd fzf kbj b kjb b jk bjkb kj bk b kjbk jbk bk bk

Post a Comment




  



Spell Checker by Foundeo

Recent Entries



foundeo


did you hack my cf?