XML reading in java
hi,
i have an XML of the form as below
<Ingredients>
<h1>VINAIGRETTE</h1>
<Ingredient>3 tablespoons Dijon or grainy mustard</Ingredient>
<Ingredient>3 tablespoons sherry or white wine vinegar</Ingredient>
<Ingredient>2 tablespoons honey</Ingredient>
<Ingredient>6 tablespoons extra-virgin olive oil</Ingredient>
<Ingredient>Salt and pepper, to taste</Ingredient>
<h1>SALAD</h1>
<Ingredient>2 heads radicchio, coarsely chopped</Ingredient>
<Ingredient>4 heads endive, coarsely chopped</Ingredient>
<Ingredient>1 bunch escarole, coarsely chopped</Ingredient>
<Ingredient>1/2 cup fresh basil leaves, shredded</Ingredient>
<Ingredient>1/4 cup minced fresh dill</Ingredient>
<Ingredient>1/4 cup flat-leaf parsley leaves</Ingredient>
</Ingredients>
how do i fetch the data after h1(VINAIGRETTE) seperately and the data after h1(SALAD) seperately.
If possible, the XML should be refactored to be a litle more well-formed, such as:
<recipes>
<recipe>
<name>Vinaigrette</name>
<ingredients>
<ingredient>3 tbsp dijon ...</ingredient>
<ingredient>3 tbsp sherry ...<ingredient>
<!-- ... -->
</ingredients>
</recipe>
<recipe>
<name>Salad</name>
<ingredients>
<ingredient>2 heads radicchio ...</ingredient>
<ingredient>4 heads endive ...</ingredient>
<!-- ... -->
</ingredients>
</recipe>
<!-- ... -->
</recipes>Such a refactoring would 1) make parsing easier; and 2) allow a more concise/rigid schema. Parsing the XML you have would be a matter of getting every element and checking the name of each one to know when to stop:
NodeList nodes = rootElement.getChildNodes();
List recipes = new ArrayList();
Recipe currentRecipe = null;
for(int i = 0, iLen = nodes.getLength(); i < iLen; i++) {
Node node = nodes.item(i);
StringBuffer textValue = new StringBuffer();
NodeList textNodes = node.getChildNodes();
for(int j = 0, jLen = textNodes.getLength(); j < jLen; j++) {
Node textNode = textNodes.item(j);
if(textNode.getNodeType() == Node.TEXT_NODE) {
textValue.append(textNode.getValue());
if("h1".equals(node.getName()) {
currentRecipe = new Recipe();
currentRecipe.setName(textValue.toString());
recipes.add(currentRecipe);
} else if("Ingredient".equals(node.getName()) && (currentRecipe != null)) {
currentRecipe.getIngredients().add(textValue.toString());
}It's a bit of a mess, and becomes more convoluted as more elements are added. Using the schema I mentioned above, you end up with a simple set of XPath expressions:
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
NodeList recipes = (NodeList)xpath.evaluate(document, "recipe", XPathConstants.NODESET);
List recipes = new ArrayList();
for(int i = 0, iLen = recipes.getLength(); i < iLen; i++) {
Node recipeNode = recipes.item(i);
Recipe recipe = new Recipe();
recipe.setName((String)xpath.evaluate(recipeNode, "name", XPathConstants.STRING));
NodeList ingredientNodes = (NodeList)xpath.evaluate(recipeNode, "ingredients/ingredient", NODESET);
for(j = 0, jLen = ingredientNodes.getLength(); j < jLen; j++) {
Node ingredientNode = ingredientNodes.item(j);
recipe.getIngredients().add(xpath.evaluate(ingredientNode, ".", XPathConstants.STRING));
}Not much better, but less ambiguous.
Similar Messages
-
XML Reading Using Java Servlet
I need some help in reading xml file using java servlet.
May i have some sample codes to read xml files?
I would really appreciate your help. Thanks!!!This grabs a url and parses it with a servlet.
URL befreeUrl = new URL(urlString);
uri = new URI(urlString);
URLConnection yc = befreeUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
factory.setValidating(true);
out = new OutputStreamWriter(System.out, "UTF8");
DefaultHandler handler = new BeFreeRequestSAXParser(); /* custom handler class */;
parser.parse(uri.toString(), handler);
in.close(); -
How to read the data from Excel file and Store in XML file using java
Hi All,
I got a problem with Excel file.
My problem is how to read the data from Excel file and Store in XML file using java excel api.
For getting the data from Excel file what are all the steps i need to follow to get the correct result.
Any body can send me the code (with java code ,Excel sheet) to this mail id : [email protected]
Thanks & Regards,
Sreenu,
[email protected],
india,If you want someone to do your work, please have the courtesy to provide payment.
http://www.rentacoder.com -
Reading XML file from java web service
Hi
I am developing web service using Netbeans and the application server is glassfish.
but I am facing a problem
I have folder called "config" which will include the xml files. What I need to do setting path into that folder
but it will read from another location when I am deploying it
How to set our own path ?
Error
DPL5306:Servlet Web Service Endpoint [NewWebService] listening at address [http://kapila.epic.lk:8080/WebApplication2/NewWebServiceService]
deployed with moduleid = WebApplication2
java.io.FileNotFoundException: /root/MyWorks/glassfish-v2/domains/domain1/config/OSconfig/MConfig.xml (No such file or directory)
at java.io.FileInputStream.open(Native Method)
My "conifg" folder, i have put in to working directory but it will read from "/root/MyWorks/glassfish-v2/domains/domain1/config/OSconfig/MConfig.xm"
below method is used for getting its contain value
public String getMainCofig() {
String v ="";
try{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("OSconfig/MConfig.xml"));
doc.getDocumentElement().normalize();
NodeList listOfSPRMs = doc.getElementsByTagName("MainConfig");
Node firstSPRMNode = listOfSPRMs.item(0);
if (firstSPRMNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstSPRAMElement = (Element) firstSPRMNode;
// Getting platform
NodeList server_port = firstSPRAMElement
.getElementsByTagName("RunningPlatform");
Element server_port_el = (Element) server_port.item(0);
NodeList server_port_List = server_port_el.getChildNodes();
v= ((Node) server_port_List.item(0))
.getNodeValue().trim();
}catch (Exception e){
e.printStackTrace();
return v;
Regards
I didn't quite get what the problem is but if the the desired file is in custom directory why don't you just use absolute path to reference it?
Like: "/home/my/OSconfig/MConfig.xml" -
Hello
Can any one help me to read XML document in JAVA
Thank uI'd use the nanoXML parser because it's small enough to fit easily on a STB.
Roger -
How to read XML files from java
i need a sugession that how to read a xml file using java code
and i need to parse using some parsers and display attributes and entity seperately
as a string.......import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.text.AttributedCharacterIterator.Attribute;
import java.util.Iterator;
import java.util.StringTokenizer;
public class XmlParser
private String Result="";
private String Final="";
private String Delim="";
public void bar1(Document document) throws DocumentException
org.dom4j.Element root = document.getRootElement();
// System.out.println(root.getName());
bar2(root);
System.out.println(this.Result);
process();
public void bar2(org.dom4j.Element e)
for(Iterator i = e.elementIterator();i.hasNext();)
org.dom4j.Element Element = (org.dom4j.Element) i.next();
Result += Element.getName()+"\t"+Element.getText()+"\n";
bar2(Element);
public void process()
StringTokenizer Tokenizer = new StringTokenizer(this.Result,"\n");
String element;
while(Tokenizer.hasMoreTokens())
element = Tokenizer.nextToken();
StringTokenizer Tokenizer2 = new StringTokenizer(element,"\t");
// Do what ever String Process here Example
this.Final += element.getName();
this.Final += this.Delim;
System.out.println(this.Final);
public static void main(String s[])throws Exception
Document document = null;
SAXReader reader = new SAXReader();
File f1= new File("D:/Rajesh/EDI to XML/EDI.xml");
document = reader.read(f1);
Demo obj = new Demo();
obj.bar1(document);
i think this will hep full....... -
Where to place an xml file that is read by java class file dir structure
Hello all,
I have an xml file that I am using in lieu of a database to track conference rooms . This is a small file. I need to read this file from my java class file which is used by a jsp. Currently I have an absolute path C://logger/conference.xml. All works fine but I need to deploy to a different machine soon and so I need to place this file somewhere in the project directory structure (created by netbeans) so that it will be included in the war file and can be read by the java class file.
Also what would be the relative path to this suggested directory.
TIA!!!public class DOMconference {
/** Creates a new instance of DOMconference */
public DOMconference() { }
//private final static String XML_FILE_NAME = "/opt/conference.xml";//set the output file and location
public String XML_FILE_NAME = "";
private final static String FIRST_CONF_ID = "8200";//set the initial conference number
static Document document;
public void getFilePath(String path)
XML_FILE_NAME = path.replaceAll("\\\\","/");
System.out.println("XML==============="+XML_FILE_NAME);
File file = new File(XML_FILE_NAME);
*generic method that returns a Document object
public Document getDocument() throws SAXException, ParserConfigurationException,
IOException
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
factory.setCoalescing(true);
factory.setNamespaceAware(false);
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(file); //HERE IS WHERE THE ERROR POINT S TO
return document;
}Here is the complete error:
INFO: Server startup in 1282 ms
XML===============C:/Documents and Settings/gforte/agi/build/web/WEB-INF/conference.xml
[Fatal Error] bin:1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException: Content is not allowed in prolog.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:264)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:292)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:172)
at agi.DOMconference.getDocument(DOMconference.java:91)
at agi.DOMconference.getLdapConferences(DOMconference.java:466)
at agi.Ldap.getConferences(Ldap.java:243)
at org.apache.jsp.test_jsp._jspService(test_jsp.java:111)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:595)
[Fatal Error] bin:1:1: Content is not allowed in prolog.
NotifyUtil::java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)
at java.io.BufferedInputStream.read(BufferedInputStream.java:313)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:606)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:554)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:571)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:936)
at org.netbeans.modules.web.monitor.server.NotifyUtil$RecordSender.run(NotifyUtil.java:248)
So if I change my code to this (note that all I change is how the constant XML_FILE_NAME is set and I copy and paste the path that is derived from getFilePath after the String.replaceAll call.):
public class DOMconference {
/** Creates a new instance of DOMconference */
public DOMconference() { }
private final static String XML_FILE_NAME = "C:/Documents and Settings/gforte/agi/build/web/WEB-INF/conference.xml";//set the output file and location
//public String XML_FILE_NAME = "";
private final static String FIRST_CONF_ID = "8200";//set the initial conference number
static Document document;
public void getFilePath(String path)
//XML_FILE_NAME = path;//.replaceAll("\\\\","/");
System.out.println("XML==============="+XML_FILE_NAME);
File file = new File(XML_FILE_NAME);
*generic method that returns a Document object
public Document getDocument() throws SAXException, ParserConfigurationException,
IOException
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
factory.setCoalescing(true);
factory.setNamespaceAware(false);
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(file);
return document;
}All is fine..
Just in case, here is my xml file contents copy and paste from notepad.
<?xml version="1.0"?><conf_rooms><conf_room><conf_id>8200</conf_id><conf_name>Conference room 1</conf_name></conf_room><conf_room><conf_id>8201</conf_id><conf_name>Conference Room 2</conf_name></conf_room><conf_room><conf_id>8202</conf_id><conf_name>dufus</conf_name></conf_room></conf_rooms>Thanks for hanging in there with me on this.
Graham -
Generation of xml file from java code
hi,
I want to manipulate data in a xml file with java code.I have read data from xml file and also changed it. But i am unable to covert it again in xml file from java code. Can you please tell me how i can do this?Let me know which parser are you using currently for reading xml files so that i assist you. For now, you can refer to STAX Parser API under this link
http://java.sun.com/webservices/docs/1.6/tutorial/doc/SJSXP3.html -
Error: unexpected XML reader state. expected: END but found: START:
I am getting following error while invoking method 'GetVersionInfo' (.net web service over dll) which takes one input parameter(string) and gives two output parameters(both short):
ERROR at line 1:
ORA-29532: Java call terminated by uncaught Java exception: deserialization
error: unexpected XML reader state. expected: END but found: START:
{UPPLink}pnVersionMajor
ORA-06512: at "SYS.UTL_DBWS", line 388
ORA-06512: at "SYS.UTL_DBWS", line 385
ORA-06512: at line 40
Expected Request is as follows:
POST /UPPLink/UPPLink.asmx HTTP/1.1
Host: 172.16.1.38
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "UPPLink/GetVersionInfo"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetVersionInfo xmlns="UPPLink">
<ignore>string</ignore>
</GetVersionInfo>
</soap:Body>
</soap:Envelope>
EXpected Response is as follows:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetVersionInfoResponse xmlns="UPPLink">
<GetVersionInfoResult>
<pnVersionMajor>short</pnVersionMajor>
<pnVersionMinor>short</pnVersionMinor>
</GetVersionInfoResult>
</GetVersionInfoResponse>
</soap:Body>
</soap:Envelope>
The PL/SQL code I am using is as follows:
DECLARE
service_ sys.utl_dbws.SERVICE;
call_ sys.UTL_DBWS.call;
service_qname sys.utl_dbws.QNAME;
port_qname sys.utl_dbws.QNAME;
operation_qname sys.utl_dbws.QNAME;
string_type_qname sys.utl_dbws.QNAME;
number_type_qname sys.utl_dbws.QNAME;
retx ANYDATA;
strEntry VARCHAR2(100);
retx_string VARCHAR2(100);
majorVersion NUMBER;
minorVersion NUMBER;
params sys.utl_dbws.ANYDATA_LIST;
v_outputs sys.utl_dbws.anydata_list;
BEGIN
dbms_output.put_line('Starting Function');
service_qname := sys.utl_dbws.to_qname(null, 'UPPLink');
strEntry := 'vab';
dbms_output.put_line('Creating Service');
service_ := sys.utl_dbws.create_service(HTTPURITYPE('http://172.16.1.38/UPPLink/UPPLink.asmx?WSDL'), service_qname);
dbms_output.put_line('Creating Operation');
operation_qname := sys.utl_dbws.to_qname(null, 'GetVersionInfo');
dbms_output.put_line('Calling Service');
call_ := sys.utl_dbws.create_call(service_, null, operation_qname);
sys.utl_dbws.set_property(call_, 'SOAPACTION_USE', 'true');
sys.utl_dbws.set_property(call_, 'SOAPACTION_URI', 'UPPLink/GetVersionInfo');
sys.utl_dbws.set_property(call_, 'OPERATION_STYLE', 'rpc');
string_type_qname := sys.utl_dbws.to_qname('http://www.w3.org/2001/XMLSchema', 'string');
number_type_qname := sys.utl_dbws.to_qname('http://www.w3.org/2001/XMLSchema', 'short');
sys.utl_dbws.add_parameter(call_, 'ignore', string_type_qname, 'ParameterMode.IN');
sys.utl_dbws.add_parameter(call_, 'pnVersionMinor', number_type_qname, 'ParameterMode.OUT');
sys.utl_dbws.set_return_type(call_, number_type_qname);
params(0) := ANYDATA.convertvarchar2(strEntry);
dbms_output.put('Invoking with Input Parameter: ');
dbms_output.put_line(ANYDATA.ACCESSVARCHAR2(params(0)));
retx := sys.utl_dbws.invoke(call_, params);
dbms_output.put_line('Invoke complete');
majorVersion := retx.accessnumber;
dbms_output.put_line('Major Version ' || majorVersion);
v_outputs := SYS.utl_dbws.get_output_values(call_);
minorVersion := ANYDATA.AccessNumber(v_outputs(1));
dbms_output.put_line('Minor Version ' || minorVersion);
sys.utl_dbws.release_service(service_);
END;
/Actually, the name needs to match what is specified in the WSDL file.
-
How to edit the existing data in the XML file from java programming.
Hi all
i am able to create XML file with the sample data as below from java programming.
i need sample code on how to edit the existing data in the XML file?
for example
<?xml version="1.0"?>
<mydata>
<data1>
<key1>467</key1>
<name1>Paul</name1>
<id1>123</id1>
</data1>
<data2>
<key2>467</key2>
<name2>Paul</name2>
<id2>123</id2>
</data2>
</mydata>
i am able to insert the data in the XML.
now i need sample code on how to modify the data in the above XML file from the java programming for only key2,name2,id2 tags only. the remaining tags data in the XML file i want to keep same data except for key2,name2,id2 which are i want to modify from java code
Regards
Sunil
[points will be always rewardable]hi
u need a parser or validate the xml file for to read the xml file from java coding u need for this
xml4j.jar u can download this file from here
http://www.alphaworks.ibm.com/tech/xml4j
or we can use the SAX(simple API for XML)
some sample applications for this
http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html
http://www.developertutorials.com/tutorials/java/read-xml-file-in-java-050611/page1.html
http://www.xml-training-guide.com/e-xml44.html
let me know u need any other info
bvr -
Hi all i am working to create a XML file using java can any one show me some sample code how to do so
All I suggested was to insert a single line ("X.serialize(root);") into your code. Anyway, here's a ready-to-compile source code based on yours. This code utilizes the Xerces-J class library.import java.io.File;
import java.io.FileWriter;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Element;
public class Test {
public static void main(String[] arguments) {
FileWriter out;
DocumentImpl d;
Element root;
XMLSerializer X;
try {
System.out.println(" creatin ");
File fos = new File("xsr.xml");
out = new FileWriter("xsr.xml");
System.out.println("created File .." + fos.getName());
out.flush();
d = new DocumentImpl();
System.out.println("create root");
root = d.createElement("abc");
System.out.println("creating element");
d.insertBefore(root, null);
//out.write(d.createAttribute(""));
OutputFormat o = new OutputFormat(d);
System.out.println("Output format...");
o.setIndent(5);
o.setIndenting(true);
o.setDoctype("lab1.dtd", "lab1.dtd");
o.setDoctype("name of dtd file", "name of dtd file");
X = new XMLSerializer(o);
X.setOutputCharStream(out);
X.serialize(root);
out.flush();
out.close();
catch (Exception e1){
e1.printStackTrace();
} -
Creating XML file from Java Bean
Hi
Are there any standard methods in Java 1.5 to create XML file from java bean,
i can use JAXB or castor to do so,
But i would like to know if there is any thing in java core classes,
I have seen XMLEncoder, but this is not what i want.
Any ideas
AshishMarshall JavaBean to an XML document with JAXB or XMLBeans.
-
How to modify an existing xml file from java code.
Hi
I have worked on creating a new xml file from java code using xmlbeans.But if i try to modify an already existing file using java code I am unable to get errorfree xmlfile.
For example if xml file(studlist.xml) is as below:
<?xml version="1.0" encoding="UTF-8"?>
<StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
<Student>
<Name>ram</Name>
<Age>27</Age>
</Student>
<Student>
<Name>sham</Name>
<Age>26</Age>
</Student>
</StudentList>
Now suppose i have set name to victor using student.setName,
and set age to 20 using setAge from javacode,
the new xml file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
<Student>
<Name>ram</Name>
<Age>27</Age>
</Student>
<Student>
<Name>sham</Name>
<Age>26</Age>
</Student>
</StudentList>
<Student>
<Name>victor</Name>
<Age>20</Age>
</Student>
As observed this is not a valid xml file.But how can i modify without any errors?I know it's an old post, but I found this while doing a google search for something else, and don't like to leave it un-aswered
Just in case anyone has a similar problem... In this case the new elements have been appended outside of the root element
What you need to do is first get the root element and then append the new children to that, there are several ways of getting the root element, which depend on what you want to do with the elements you get back here's a simple (incomplete) way.
// gets the root element of the specified file (code not shown)
Element rootElement= new SAXReader().read(file).getRootElement();Then just append the new elements as below (this is non-generic code and would need to be modified for your situation)
// write a new student element
Element student = document.createElement("Student"); // creates the new student
rootElement.appendChild(student); // ***appends it to the root element***
Element name = document.createElement("Name"); // creates the name element
name.appendChild(document.createTextNode("Fred")); // adds the name text to the name element
student.appendChild(name); // appends the name to the student
Element age= document.createElement("Age"); // creates the age element
age.appendChild(document.createTextNode("26")); // adds the age text to the age element
student.appendChild(age); // appends the name to the studentThen flush ya buffers or whatever and write the file
Edited by: Dream-Scourge on Apr 23, 2008 11:10 AM -
How to write as XML file using java 1.5
hi all,
i am trying to create an XML file using java 1.5. I took a XML creating java file which was working with java 1.4 and ported same file into java 1.5 with changes according to the SAX and DOM implmentation in java 1.5 and tried to compile. But while writing as a file it throws error "cannot find the symbol."
can any body help me out to solve this issue.......
thankx in advance
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.NamedNodeMap;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.DocumentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.ParserFactory;
import java.io.*;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document xmlDoc = db.newDocument();
// this creates the xml document ref
// parent node reference
Element rootnd = (Element) xmlDoc.createElement("ALL_TABLES");
// root node
xmlDoc.appendChild(rootnd);
Element rownd = (Element) xmlDoc.createElement("ROW");
rootnd.appendChild(rownd);
Element statusnd = (Element) xmlDoc.createElement("FILE_STATUS");
rownd.appendChild(statusnd);
statusnd.appendChild(xmlDoc.createTextNode("Y")
FileOutputStream outpt = new FileOutputStream(outdir + "//forbranch.xml");
Writer outf = new OutputStreamWriter(outpt, "UTF-8");
//error is occuring here Since write method is not available in the Document class
xmlDoc.write(outf);
outf.flush();Hi,
when I look in the JDK1.4.2 specification I don't see any write method in the Document interface.
However, your solution is the Transformer class. There you transform your DOM tree into any output you need. Your code sould look something like this: TransformerFactory tf = TransformerFactory.newInstance();
// set all necessary features for your transformer -> see OutputKeys
Transformer t = tf.newTransformer();
t.transform(new DOMSource(xmlDoc), new StreamResult(file));Then you have your XML file stored in the file system.
Hope it helps. -
How many web.xml in a java application
Hi,
can anyone give tell the answer for this question "How many web.xml in a java application?"1Why ?Because the Web container refers to only one web.xml for one web application.
I havent heard of an application having more than 1 web.xml
How?It reads all the definitions of servlet mappings, filters, welcome-file etc from this file itself.
Where?From the following folder ...
/WEB-INF
By the way ..... the way you questioned me was amuzing ... Why? How ?Where ? Its funny :D
I actually wanted to reply as below ..
Why ?Why not
How?
Wait lemme think ....ummm... What do you mean how??
Where ?
Inside the web ;-)
-Rohit
Maybe you are looking for
-
How to create a folder for a specific e-mail account?
How to create a folder for a specific e-mail account? I'm using a POP e-mail account and I would like to create folders / sub-folders... how can I do this?
-
Reg. module pool....have ur points..
Hi all, In module pool programming, we see "MODULE CANCEL AT EXIT-COMMAND" in PAI. Pleas let me know the meaning of this in simple language..... <b>n Have ur points.</b>
-
Hello Everyone, we are hoping for some help in deploying one of the tutorial applications. Currently we are testing out the JDeveloper 10g preview application. We''ve been able to follow a few of the tutorials, although it seems that at least half ha
-
I have an issue where I can only bind one of my 2 machines to OD. All should be setup correctly as one machine has no problem binding. The second machine tells me that the credentials i supplied are incorrect. The first machine will bind with no prob
-
I know how to use javabean. But I don't know how to make a transparent frame .Can anyboy help me?If you have code ,please send to me .I thanks a lot . Email: [email protected]