How to Parse a string into an XML DOM ?
Hi,
I want to parse a String into an XML DOM. Not able to locate any parser which supports that. Any pointers to this?
Download Xerces from xml.apache.org. Place the relevant JAR's on your classpath. Here is sample code to get a DOM document reference.
- Saish
public final class DomParser extends Object {
// Class Variables //
private static final DocumentBuilder builder;
private static final String JAXP_SCHEMA_LANGUAGE =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
/** W3C schema definitions */
private static final String W3C_XML_SCHEMA =
"http://www.w3.org/2001/XMLSchema";
// Constructors //
static {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException e) throws SAXException {
System.err.println("[warning] "+e.getMessage());
public void error(SAXParseException e) throws SAXException {
System.err.println("[error] "+e.getMessage());
public void fatalError(SAXParseException e) throws SAXException {
System.err.println("[fatal error] "+e.getMessage());
throw new XmlParsingError("Fatal validation error", e);
catch (ParserConfigurationException fatal) {
throw new ConfigurationError("Unable to create XML DOM document parser", fatal);
catch (FactoryConfigurationError fatal) {
throw new ConfigurationError("Unable to create XML DOM document factory", fatal);
private DomParser() {
super();
// Public Methods //
public static final Document newDocument() {
return builder.newDocument();
public static final Document parseDocument(final InputStream in) {
try {
return builder.parse(in);
catch (SAXException e) {
throw new XmlParsingError("SAX exception during parsing. Document is not well-formed or contains " +
"illegal characters", e);
catch (IOException e) {
throw new XmlParsingError("Encountered I/O exception during parsing", e);
}- Saish
Similar Messages
-
How to write a string into an XML
I wrote a web service to receive a string and write to Oracle Application Server as XML Document. But It is not writing anything. Below is writer program. What do I need to add to make it work
public class Writer
public Writer()
} public void WriteHabFile(String out, String fileName)
XMLDocument doc = new XMLDocument();
try
XMLPrintDriver output=new XMLPrintDriver(new FileOutputStream(new File(fileName)));
output.setEncoding("utf-8");
output.printDocument(doc);
output.close();
catch (Exception e)
System.out.println(e.toString());
public void WriteLanFile(String out2, String fileName2)
XMLDocument doc = new XMLDocument();
try
XMLPrintDriver output=new XMLPrintDriver(new FileOutputStream(new File(fileName2)));
output.setEncoding("utf-8");
output.printDocument(doc);
output.close();
catch (Exception e)
System.out.println(e.toString());
Any help would be greatly appreciated.Why don't you try something like:
public class Writer {
public Writer(){}
public void WriteHabFile(String out, String fileName) {
oracle.xml.parser.v2.DOMParser parser = new oracle.xml.parser.v2.DOMParser();
try {
parser.parse(new BufferedReader(new StringReader(out)));
catch(XMLParseException xe) {
// Do Something
catch(SAXException se) {
// Do Something
catch(IOException ie) {
// Do Something
XMLDocument doc = parser.getDocument();
try {
XMLPrintDriver output=new XMLPrintDriver(new FileOutputStream(new File(fileName)));
output.setEncoding("utf-8");
output.printDocument(doc);
output.close();
catch (Exception e)
System.out.println(e.toString());
public void WriteLanFile(String out2, String fileName2) {
oracle.xml.parser.v2.DOMParser parser = new oracle.xml.parser.v2.DOMParser();
try {
parser.parse(new BufferedReader(new StringReader(out)));
catch(XMLParseException xe) {
// Do Something
catch(SAXException se) {
// Do Something
catch(IOException ie) {
// Do Something
XMLDocument doc = parser.getDocument();
try {
XMLPrintDriver output=new XMLPrintDriver(new FileOutputStream(new File(fileName2)));
output.setEncoding("utf-8");
output.printDocument(doc);
output.close();
catch (Exception e)
System.out.println(e.toString());
Hope this helps,
Mark Brown -
How to convert Java string into XML one?
With SAX I can parse an xml file, but I should create xml file by hands.
Ok, it's simple, but how to encode java string into XML constant
like "Hello & goodby" into "Hello & goodby" ?
Is there a standard method for such special xml characters?If you are creating your XML "by hand" then just make sure your hands know that you have to do that. It isn't difficult to write a Java method to do it, if "by hand" means "in Java code". Otherwise your XML is not well-formed. And as far as I know there is no package that takes ill-formed XML and fixes it up.
-
A class to format an XML string into indented xml code
I am looking for a class or a piece of code to format an XML string into indented xml code
for example: an XML string as follows
<servlet><servlet-name>Login</servlet-name>servlet-class>ucs.merch.client.system.LoginServlet</servlet-class></servlet><servlet-mapping><servlet-name>Login</servlet-name>
to format into :
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>ucs.merch.client.system.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
e-mail : [email protected]Xerces has a class called OutputFormat
If you have your XML document in memory, you can format it using the method setIndenting(true) on the OutputFormat class. The following is an example:
assuming xmlDoc is our document and fileName is the name of the file we wish to write to:
OutputFormat format = new OutputFormat(xmlDoc);
// setup output file name
PrintWriter printwriter = new PrintWriter(new FileWriter(fileName, false));
// construct an XMLSerializer for writing the document
XMLSerializer serializer = new XMLSerializer( printwriter, format );
// Ensure output is indented correctly...
format.setIndenting(true);
// set serializer as a DOM Serializer
serializer.asDOMSerializer();
// serialize the document
serializer.serialize(xmlDoc);
hope this helps!
Rob. -
How to convert HL7 file into an XML
Hi All,
I am new to HL7,can any one tell how to convert HL7 file into an XML.Give sample demo or related links.
My sample HL7 file is as follows how can I convert.
FHS|^~\&||Tax ID123^Lab Name123^L|||201110191435||HL7.txt||1234567|123||
PID|seqno|123||john^chambers^^Dr^Dr|2456 california ave^San jose^CA^85254|19601212|M
FHS|^~\&||Tax ID123^Lab Name123^L|||File Creaqted Date|File Security|FileName||File HeaderComment||Facility|FileCreatedDateTime|File Security|File Name|File Header Comment|FileControlId|Reference File Control ID|
PID|seqno|patientId||LastName^FirstName^MiddleName^Title^Degree|Street^City^State^zip|patientDOB|gender
<Report>
<FileHeader>
<FileSendingApplication> </FileSendingApplication>
<TaxID>Tax ID123</TaxID>
<LabName>Lab Name123</LabName>
<FileSendngFacilityType>L</FileSendngFacilityType>
<FileReceivingApplication></FileReceivingApplication>
<FileReceivingFacility></FileReceivingFacility>
<FileCreatedDateTime>201110191435</FileCreatedDateTime>
<FileSecurity></FileSecurity>
<FileName>HL7.txt</FileName>
<FileHeaderComment></FileHeaderComment>
<FileControlId>1234567</FileControlId>
<ReferenceFileControlID></ReferenceFileControlID>
<FileHeader>
<Patient>
<seqno> </seqno>
<patientId>Tax ID123</patientId>
<LastName>Lab Name123</LastName>
<FirstName>L</FirstName>
<MiddleName></MiddleName>
<Title> </Title>
<Degree></Degree>
<Street></Street>
<City></City>
<State>HL7.txt</State>
<Zip></Zip>
<patientDOB>1234567</patientDOB>
<gender></gender>
<Patient>
</Report>
Thanks
ManiHi Prabu,
With input as in single line I'm able to get the the output but with the multiple lines of input,error was occured.Any suggestions.
Error while translating. Translation exception. Error occured while translating content from file C:\temp\sampleHL7.txt Please make sure that the file content conforms to the schema. Make necessary changes to the file content or the schema.
The payload details for this rejected message can be retrieved. Show payload...
Thanks
Mani -
How to Splilit The String Into Single Column using Comma As Delimiter ?
How to Splilit The String Into Single Column using Comma As Delimiter ?
using Functionrefer my thread ,code is also available see if that helps you
error while executing the sp ORA-21779: duration not active -
How to parse a string containing xml data
Hi,
Is it possible to parse a string containing xml data into a array list?
my string contains xml data as <blood_group>
<choice id ='1' value='A +ve'/>
<choice id ='2' value='B +ve'/>
<choice id ='3' value='O +ve'/>
</blood_group>how can i get "value" into array list?There are lot of Java XML parsing API's available, e.g. JAXP, DOM4J, JXPath, etc.
Of course you can also write it yourself. Look which methods the String API offers you, e.g. substring and *indexOf. -
How to convert a string into xml file
Hi,
i have a string . the string contain fully formated xml data. i mean my string like below
<?xml version="1.0"?>
<PARTS>
<TITLE>Computer Parts</TITLE>
<PART>
<ITEM>Motherboard</ITEM>
<MANUFACTURER>ASUS</MANUFACTURER>
<MODEL>P3B-F</MODEL>
<COST> 123.00</COST>
</PART>
<PART>
......................i want to convert it into an xml file
can u help me?
thank uThank you Paul Clapham,
and sorry ..
i have some other doubt.. regarding xml
i want to post an XML file from one server(Server_1) to other server.(Server_2)
To generate an xml file i used DOM in Server_1.
using xml.transform , StringWriter i converted it into String.
I post the string to another server and there i will parse it.
for that i write the code like below in servlet in server_1
<form name=fn action=http://localhost:8080/server_2/parseXMl.do method=post>
<input type=hidden name=xmlFile value="+Xmlstring+">
<input type=submit >is this process is correct?
Some of the turorial told that use web-services/XML-RPC
but i new to both..
I want to complete it using my knowledge only/
Is it possible to do it?
Or any other alternative?
can help me? -
How to parse and retrieve records from xml files into columns in Table
Hi
I attached the thing what i tried.
Table to hold the XML COntent:
create table xmlfile(xml_con sys.xmltype);
Inserting Xml file content into the Above table:
insert into xmlfile values(sys.xmltype.CreateXml('<Root><name>RAM</name><age>23</age></Root>'))
SQL> select * from xmlfile;
XML_CON
<Root>
<name>RAM</name>
<age>23</age>
</Root>
SQL> select extractValue(xml_con, '/Root/name') content from xmlfile;
CONTENT
RAM
This one works fine
But if the file content is as below( contains MUltiple Records)
insert into xmlfile values(sys.xmltype.CreateXml('<Root><Record><name>RAM</name><age>23</age></Record><Record><name>SAM</name><age>23</age></Record></Root>'))
SQL> select extractValue(xml_con, '/Root/Record/name') content from xmlfile;
ERROR at line 1:
ORA-19025: EXTRACTVALUE returns value of only one node
Can anyone help me 4 this issue-How to extract multiple records from the XML file inthis manner(from PL/SQL without using JAVA)
OR
If there is anyother way to do this please tell me?SQL> SELECT EXTRACTVALUE (COLUMN_VALUE, '//name') NAME,
EXTRACTVALUE (COLUMN_VALUE, '//age') age
FROM TABLE
(XMLSEQUENCE
(EXTRACT
(XMLTYPE
('<Root>
<Record>
<name>RAM</name>
<age>23</age>
</Record>
<Record>
<name>SAM</name>
<age>23</age>
</Record>
</Root>'
'/Root/Record'
NAME AGE
RAM 23
SAM 23
2 rows selected. -
Hi,
I need to parse,in CVP 7.0(1), the BAAccountNumber variable passed by the ICM dialer. Is there a built-in java class or other function that would help me do this?
Our BAAccountNumber variable looks something like this: 321|XXX12345678|1901|M. In IP IVR I use the "Get ICM Data" object to read the BAAccountNumber variable from ICM and then I use the "token index" feature to parse the variable (picture below).
Alternately, IP IVR also has a Java class that allows me to do this; the class is "java.lang.String" and the method is "public int indexOf(String,int)"
Is there something equivalent in CVP 7.0(1)?
thanksThanks again for your help. This is what I ended up doing:
This configurable action element takes a string seperated by two "|" (123|123456789|12)
and returns 3 string variables.
you can add more output variables by adding to the Setting array below.
// These classes are used by custom configurable elements.
import com.audium.server.session.ActionElementData;
import com.audium.server.voiceElement.ActionElementBase;
import com.audium.server.voiceElement.ElementData;
import com.audium.server.voiceElement.ElementException;
import com.audium.server.voiceElement.ElementInterface;
import com.audium.server.voiceElement.Setting;
import com.audium.server.xml.ActionElementConfig;
public class SOMENAMEHERE extends ActionElementBase implements ElementInterface
* This method is run when the action is visited. From the ActionElementData
* object, the configuration can be obtained.
public void doAction(String name, ActionElementData actionData) throws ElementException
try {
// Get the configuration
ActionElementConfig config = actionData.getActionElementConfig();
//now retrieve each setting value using its 'real' name as defined in the getSettings method above
//each setting is returned as a String type, but can be converted.
String input = config.getSettingValue("input",actionData);
String resultType = config.getSettingValue("resultType",actionData);
String resultEntityID = config.getSettingValue("resultEntityID",actionData);
String resultMemberID = config.getSettingValue("resultMemberID",actionData);
String resultTFNType = config.getSettingValue("resultTFNType",actionData);
//get the substring
//String sub = input.substring(startPos,startPos+numChars);
String[] BAAcctresults = input.split("\\|");
//Now store the substring into either Element or Session data as requested
//and store it into the variable name requested by the Studio developer
if(resultType.equals("Element")){
actionData.setElementData(resultEntityID,BAAcctresults[0]);
actionData.setElementData(resultMemberID,BAAcctresults[1]);
actionData.setElementData(resultTFNType,BAAcctresults[2]);
} else {
actionData.setSessionData(resultEntityID,BAAcctresults[0]);
actionData.setSessionData(resultMemberID,BAAcctresults[1]);
actionData.setSessionData(resultTFNType,BAAcctresults[2]);
actionData.setElementData("status","success");
} catch (Exception e) {
//If anything goes wrong, create Element data 'status' with the value 'failure'
//and return an empty string into the variable requested by the caller
e.printStackTrace();
actionData.setElementData("status","failure");
public String getElementName()
return "MEDDOC PARSER";
public String getDisplayFolderName()
return "SSC Custom";
public String getDescription()
return "This class breaks down the BAAccountNumber";
public Setting[] getSettings() throws ElementException
//You must define the number of settings here
Setting[] settingArray = new Setting[5];
//each setting must specify: real name, display name, description,
//is it required?, can it only appear once?, does it allow substitution?,
//and the type of entry allowed
settingArray[0] = new Setting("input", "Original String",
"This is the string from which to grab a substring.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[1] = new Setting("resultType", "Result Type",
"Choose where to store result \n" +
"into Element or Session data",
true, // It is required
true, // It appears only once
false, // It does NOT allow substitution
new String[]{"Element","Session"});//pull-down menu
settingArray[1].setDefaultValue("Session");
settingArray[2] = new Setting("resultEntityID", "EntityID",
"Name of variable to hold the result.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[2].setDefaultValue("EntityID");
settingArray[3] = new Setting("resultMemberID", "MemberID",
"Name of variable to hold the result.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[3].setDefaultValue("MemberID");
settingArray[4] = new Setting("resultTFNType", "TFNType",
"Name of variable to hold the result.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[4].setDefaultValue("TFNType");
return settingArray;
public ElementData[] getElementData() throws ElementException
return null; -
How to write input data into an xml file
Hi All,
I have some input data and i have to write it
into an xml file.How is it possible send me some related
links regarding this and source code if any.Hi
Try to go through these links.I hope this will help you to solve your problem.
http://www.xml.com/pub/a/2003/07/09/udell.html
Thanks
Mrutyunjaya Tripathy -
How to put a String into a byte array
How can i put a String into a byte array byte[]. So that i can send it to the serial port for output to an LCD display. Cheers David
javadocs for String
getBytes
public byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
Returns:
The resultant byte arraySince:
JDK1.1 -
How to export special characters into an XML file?
Dear experts,
We read files from our customers and save data into our customized table without any character changed, including some address fields. In those address fields, some special characters (not in our code page) are also kept. When we want to write these address fields into an XML file or flat file, the special charcters become "##" or not readable, can anyone help us to solve this issue?
Question1: How to write special code to an external file?
Question2: how to use 'CALL TRANSFORMATION' from an internal table to an XML file?
Your answer is highly appreciated!
JoanneHi Joanne.
Please check the below link.
CALL TRANSFORMATION
Before that u have to create one transformation program in STRANS tcode for using it in call transformation statement.
Hope it will be useful.
Regards,
Lakshman -
How to convert a string into orcle date format
i need some information about converting string into date format.i have string like '20-SEP-05' .so we have to convert into date formate like yy-mm-dd' (2005-09-20).how can we do it.
Here's some code to help. I can't remember what method uses what format though
public static java.sql.Date sqlDateValueOf( String dateString ) {
String stringDate = null;
if ( dateString == null || dateString.length() < 10 ) return null;
String strDay = "";
String strMonth = "";
String strYear = "";
if ( dateString.substring(4,5).equals( "-" ) ) {
strDay = dateString.substring(8, 10);
if ( strDay.length() < 2 ) strDay = "0" + strDay;
strMonth = dateString.substring(5, 7);
strMonth = dateString.valueOf(Integer.parseInt(strMonth) - 1);
if ( strMonth.length() < 2 ) strMonth = "0" + strMonth;
strYear = dateString.substring(0, 4);
stringDate = strDay + "-" + strMonth + "-" + strYear;
else if ( dateString.substring(2,3).equals( "-" ) ) {
strDay = dateString.substring(0, 2);
if ( strDay.length() < 2 ) strDay = "0" + strDay;
strMonth = dateString.substring(3, 5);
strMonth = String.valueOf(Integer.parseInt(strMonth) - 1);
if ( strMonth.length() < 2 ) strMonth = "0" + strMonth;
strYear = dateString.substring(6, 10);
stringDate = strDay + "-" + strMonth + "-" + strYear;
Calendar cal = Calendar.getInstance();
cal.set( Calendar.YEAR, Integer.parseInt( strYear ) );
cal.set( Calendar.MONTH, Integer.parseInt( strMonth ) );
cal.set( Calendar.DAY_OF_MONTH, Integer.parseInt( strDay ) );
java.sql.Date outDate = new java.sql.Date( cal.getTimeInMillis() );
return outDate;
public static String toDateString( java.util.Date date) {
if ( date == null || date.toString().length() < 10 ) return null;
String outDate = "";
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
outDate = df.format( date );
return outDate;
public static String toDateString( java.sql.Date date) {
if ( date == null || date.toString().length() < 10 ) return null;
String outDate = "";
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
outDate = df.format( date );
return outDate;
public static String toDateString( java.sql.Date date, String format) {
if ( date == null || date.toString().length() < 10 ) return null;
String outDate = "";
SimpleDateFormat df = new SimpleDateFormat( format );
outDate = df.format( date );
return outDate;
public static String toDateString( java.sql.Timestamp date) {
if ( date == null || date.toString().length() < 10 ) return null;
String outDate = "";
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
outDate = df.format( date );
return outDate;
} -
Easy Question: How to split concatenated string into multiple rows?
Hi folks,
this might be an easy question.
How can I split a concatenated string into multiple rows using SQL query?
INPUT:
select 'AAA,BBB,CC,DDDD' as data from dualDelimiter = ','
Expected output:
data
AAA
BBB
CCC
DDDDI'm looking for something kind of "an opposite for 'sys_connect_by_path'" function.
Thanks,
TomasHere is the SUBSTR/INSTR version of the solution:
SQL> WITH test_data AS
2 (
3 SELECT ',' || 'AAA,BBB,CC,DDDD' || ',' AS DATA FROM DUAL
4 )
5 SELECT SUBSTR
6 (
7 DATA
8 , INSTR
9 (
10 DATA
11 , ','
12 , 1
13 , LEVEL
14 ) + 1
15 , INSTR
16 (
17 DATA
18 , ','
19 , 1
20 , LEVEL + 1
21 ) -
22 INSTR
23 (
24 DATA
25 , ','
26 , 1
27 , LEVEL
28 ) - 1
29 ) AS NEW_STRING
30 FROM test_data
31 CONNECT BY LEVEL <= LENGTH(REGEXP_REPLACE(DATA,'[^,]','')) - 1
32 /
NEW_STRING
AAA
BBB
CC
DDDD
Maybe you are looking for
-
How can I take a picture of a camera output on the Front panel
Hi all, I've been fighting this one for a while, But I have a DataRay WinCamD CCD image in my front panel, I need a way of saving that image to a file. I've been crawling through NI Vision and IMAQ VIs and I can seem to piece the process together. Th
-
Performance of XI Integration Engine
Hi, Scenario: RFC <=> PI <=> HTTP In our landscape, we have more number of RFC to HTTP interfaces(syn). I need to know about the effect in the performance of PI Integration Engine as messages per sec will be large. Specifically, how RFC Adapter will
-
Hi, In February, we had downloaded the manual bank statement (FF67), unfortunately, we had clicked wrong. After finding the problem, we tried to make a new posting but the system did not accept the second posting. In fact, the transactions should
-
No internet with macbookpro closed
I have just set up my Macbook Pro with an external display. When I attempt to use the internet with the laptop closed ( USB keyboard and bluetooth mouse) the internet loses one bar of signal strength( down to three bars) and will not connect. The m
-
E51 - incoming caller name not displayed
Hello, I am having this bizarre problem with my new E51. I cannot see any details of incoming calls. Moreover when I go to missed calls, it always displays as 'unknown'. All contacts have their first name and last name populated correctly. Also I hav