Parsing, Modifying, and outputting XML Documents with Java

August 16, 2005
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);


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

Comments

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);
that should be transformer.transform() I will update
Thank you..your explenation is perfect
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!!!
i am having the same problem as the person above, i need to update the actual xml file. Please help!
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.
thanks for the explanation...helped a lot
Good piece of code...working & yes with a line modification you can write the changes to the same file
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.
Can any one tell how to format a xml file through java program.
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 !!!!
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 !!!!
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
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.
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
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.
Good Article. Accept my appreciation .
Very Good One. Helped me a lot. Thanks.
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?
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.
Excellent article, took me out of difficulties, thank you.
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
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>
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 ?
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!
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
<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....
<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
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.
Thankx for the help....it worked for me :)
hai ur explanation is nice.it helps everyone to solve problems while creatinfg xml thanks.
Hi, please tell me how to sort this xml file, if i m updating it on runtime.
i want to add particular attribute into the paticular coloumn
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
Hi, i want to read (separate) the attributes of xml file without using tagname in java. please help me. Thanks.
Hi, Does this code handles reading very large XML files.. say around 1 GB in size? How to read those files? Thanks
http://www.forex.co.ir http://www.meta-fx.com forex ?????
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.
Hi, I also get [#document : null] when using DocumentBuilderFactory... does anyone have a reason/solution for this?
thx for the help buddy... urz is the first link wen ne1 doez a google search fr thz query.... gr8 work... thxx :)
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.
How can I add element in such a manner. <?xml version="1.0" ?> <Global> <earth> <country>us</country> </earth>
Sorry! It will be <?xml version="1.0" ?> <Global><earth> <country>us</country> </earth></Global>
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
Hi, I am new to xml can anyone send which site and material is good. Thanks alot for advance
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.
the Indentaion works in windows but somehow is not working in linux... where cud i have possiblely gone wrong... plz help...
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
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..
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(); } } }
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(); } } }
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>
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?
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")));
thanks for giving the idea of using transformerfactory.
very good, but how could i modify value of existing node
Thanks - very concise and a great help. Saved me a few hours!
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....
hi, i want a piece of code that would read data froma database(MySql) and convert it into Xml file. plz help!!!
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.
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
can you please let me know how can we modify the value of a particular attribute in a XML document.
can you please let me know how can we modify the value of a particular attribute in a XML document.
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 ..
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()); }
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); } } }
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>
The above example is by krishnan@vigshakri.com
By www_vigshakri_com
Really nice code. Above code actually converts xmltext of document to string
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.
VTD-XML allows you to modify XML documents incrementally...
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?
Can I get complete set of code for Parsing, Modifying, and outputting XML Documents with Java
this program???
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>
the remove xml declaration works in windows but it's not working in linux... is there any way to get this to work?
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");
You may want to look at vtd-xml, the latest open source xml parsing/xpath/indexing lib

http://vtd-xml.sf.net
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();
}


}
nice code
it really helped me
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
Great help it works for me. Thnx
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
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
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
thanks Kevin,
do u have any idea about csv(comma seprated values) file format. if plz let me know.
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 ?
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
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.
sir,i need your help in providing interface for reading and writing the xml content in jsp....
Amiable post and this post helped me alot in my college assignement. Say thank you you as your information.
hi,
thank for you...your providing this Good Article.nice code it really helped me.
__________________________
angelthomos
thank for you.. providing this code is very helpme.
Hey,

Can I read some value from my external file (Text etc) in my XML File?
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"?>
"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))
how do i marshall java classes to xml documents without declaring the object name?
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..
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..
Hi, The Way you made the Steps to Explain is Excellent which makes To Understand at all level of programmers. Thank you
xml' already exists in this location. do u want to replace it?
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.
Will the north star (polaris) always be the north star?
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!
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.
Why do we change foriegn place names to other than the real name? Example being Munchen or Munich?
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.
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
i need sample example to append multiple child nodes to the parent nodes in xml file
Hi Pete Freitag,
Your article about xml with java is perfect and I am not able to pay you thank for your effort.
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
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.
I Need to read a pdf from URL and parse it to XML using java. can anyone help to do this process.
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?
how can i save the newly modified xml document into another xml document
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) {
}
}
please how to insert the data into xml floder its urgent
sample java code to dd data to xml file from java program
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....
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
i have got error here
Document doc = docBuilder.parse("/path/to/file.xml");


cant find symbol
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?
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?