Parsing an xml string into id-value pair format
Hi,
I am new in oracle BPEL.
My requirement is that I need to parse an xml string containing tag name and coressponding value into an 'id -value' pair.
For example-
The input xml format is -
<employee>
<empid>12345</empid>
<name>xyz</name>
<city>London</city>
</employee>
The required xml format is-
<employee>
<item id="empid" value="12345"/>
<item id="name" value="xyz"/>
<item id="city" value="London"/>
</employee>
Please let me know if there is a work-around for this.
Thanks
Something like this (have not tested):
<xsl:for-each select="//employee">
<employee>
<xsl:for-each select="./*">
<item>
<xsl:attribute name="id">
<xsl:value-of select="name()"/>
</xsl:attribute>
<xsl:attribute name="value">
<xsl:value-of select="text()"/>
</xsl:attribute>
</item>
</xsl:for-each>
</employee>
</xsl:for-each>
Similar Messages
-
Parsing input stream into named value pairs
Hi everyone. I figured I would post this scenario, and hope to get some 'expert' opinions on what the best way to handle this would be.
I have an input stream being returned to me and I need to separate them into name/value pairs. I receive this as two lines of strings. The first line is the variable names, and the second line is the values. This is the format:
"Variable1","Variable2","Variable3","Variable4"
"Value1","Value2","Value3","Value4"
I need to separate this out into:
Variable1 = "Value1"
Variable2 = "Value2"
What I was thinking of doing is to create a hashtable, read the first line in and assign those as the keys, then read the second line in and assign those as the values. I'm not quite sure if this is even possible as of yet, but thats my original game plan. My primary goals are:
1. Seperate each variable name and match it with its appropriate value
2. Be able to retrieve each value by calling the appropriate variable name.
Any advice/opinion on this is greatly appreciated!!! Thanks!You could choose to feed the String through an InputStream and use a StreamTokenizer, which is substantially more powerful than StringTokenizer. I would personally, however, choose to parse it myself, as antequated as that might seem. ;)
Presume that s1 is equal to
"Var1", "Var2", "MoreVars", "EvenMoreVars" , "LastVar"
And that s2 is equal to
"Hello","9900", ":)", "He said \"hi\".", "Hi, there."
These would make good sample data, but aren't necessarily the case.
String s1 = ...;
String s2 = ...;
HashMap map = null;
String[] keys = parseQuotedByCommas(s1);
String[] values = parseQuotedByCommas(s2);
if (keys.length==values.length)
map = new HashMap();
for (int i=0;i<keys.length;i++)
map.put(keys, values[i]);
} else
// Error!
// throws IllegalArgumentException for improperly formatted strings
public static String[] parseQuotedByCommas(String s)
ArrayList acc = new ArrayList();
char[] ch = s.toCharArray();
int i = 0;
try
while (i < ch.length)
while (ch[i] == ' ') i++;
if (i < ch.length)
if (ch[i] != '"')
throw new IllegalArgumentException(
"Expected '\"', receieved '" + ch[i] + "'");
i++;
StringBuffer sb = new StringBuffer();
boolean stop = false;
while (!stop)
switch (ch[i])
case '"':
if (ch[i - 1] == '\\')
sb.append('"');
else
stop = true;
break;
case '\\':
int j = i;
boolean write = true;
while ((j >= 0) && (ch[j] == '\\'))
write = !write;
j--;
if (write) sb.append('\\');
break;
default:
sb.append(ch[i]);
i++;
acc.add(sb.toString());
if (i < ch.length)
while (ch[i] == ' ') i++;
if (i < ch.length)
if ((ch[i] != ',') && (ch[i] != '"'))
throw new IllegalArgumentException(
"Expected ',' or '\"', received '" + ch[i] + "'");
i++;
} catch (IndexOutOfBoundsException oob)
throw new IllegalArgumentException("Unexpected end of string.");
return (String[]) (acc.toArray(new String[0]));
That should work for anything formatted as
<String> ::= [<WhiteSpace>] <Stmt> [ [<WhiteSpace>] , [<WhiteSpace>] <Stmt> ] *
<Stmt> ::= " <Characters> "
<Characters> ::= \" | \\ | <AnyCharacterExceptQuoteOrBackslash>
<WhiteSpace> ::= <Space>*
Any questions?
Oh, BTW, that was all blue 'cause the code tag doesn't take well to '"'. -
How to get an xml string into a Document w/o escaping mark-up characters?
Hi,
I am using one of the latest xerces using Java. I am pretty sure I am using xerces-2.
I have an existing Document and I am trying to add more content to it. The new content itself is xml string. I am trying to insert this xml string into the document using document.createTextNode. I am able to insert, but somewhere it is escaping the mark-up characters (<,>,etc). When I convert the document into String, I can see, for example, <userData> instead of <userData>.
There is an alternative option to accomplish this by creating a new document with this xml string, get the root element, import this element into my document. Execution time for this procedure is very high - means, this is very bad in terms of time-wise performance.
Can any help on how to accomplish this (bringing an xml string into a document without escaping mark-up characters) in time-efficient way.So you want to treat the contents of the string as XML rather than as text? Then you have to parse it.
Or if your reason for asking is just that you don't like the look of escaped text, then use a CDATA section to contain the text. -
Hi all,
I have a question here regarding converting XML string into a DOM document.
How can I do this in Java?
The Document.Parse() methods do not have one that takes in String as its parameter.
I'm not sure what is the best way to do this in Java.
Any help is greatly appreciated.
Thank you in advance.
regards,
SeanConvert XML String to Document with StringReader.
String xmlString;
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString))); -
REG: WRITE XML STRING INTO XML FILE
Hi All, I have a XML FILE on PC. I get a xml string from my server.
My Task: I want to append the xml string coming from the server into the existing xml file at a particular Node. Given below is my code :
String xmlString = baos.toString();
DocumentBuilder db4XMLString = docBuilderFactory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlString));
Document doc4XMLString = db4XMLString.parse(inStream);
Node root4XMLString = doc4XMLString.getElementsByTagName("epg").item(0);
doc.appendChild(doc.importNode(root4XMLString, true));
File file = new File(Constant.XMLFILEPATH);
Result result = new StreamResult(file.toURI().getPath());
Source source = new DOMSource(doc);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);But, wen i run my application I get following exception:
The markup in the document following the root element must be well-formed.
org.xml.sax.SAXParseException: The markup in the document following the root element must be well-formed.
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
Is that my XML string is not well formed. Is it so then please let me how to convert my xml string into well formed XML data.
Please help me out.
Thanking You.There are many reasons why xmlString could be not well formed. There is no magic recipe for making it well formed: just look at it and see why it is not parseable.
Note that this line:
String xmlString = baos.toString();can be problematic if you have non ASCII-7 characters in your XML document. baos could then contain a byte representation of these characters in one particular encoding, but, since you use the .toString() method that relies on the default encoding of your system, you can end up with a mismatch and garbage in your XML. -
How would I get the Oracle XML Parser to parse an XML string?
The example ("DOMSample") only demonstrates how to parse an XML
file -- I would like to do something of the form...
parser.parse("<test>testing</test>");
On a related note, whilst the PL/SQL utilities are helpful, I
would like to see more in the way of documentation and examples
for the Parser itself, showing more examples of DOM API calls and
perhaps a complete worked example (including a DTD).
Keep up the good work!
Many thanks,
Ian Brettell,
Indus International.
nullIan Brettell (guest) wrote:
: How would I get the Oracle XML Parser to parse an XML string?
: The example ("DOMSample") only demonstrates how to parse an XML
: file -- I would like to do something of the form...
: parser.parse("<test>testing</test>");
With the latest version, 1.0.0.1, now available, you can use the
InputStream and InputSource methods. Please see the doc for
details.
: On a related note, whilst the PL/SQL utilities are helpful, I
: would like to see more in the way of documentation and examples
: for the Parser itself, showing more examples of DOM API calls
and
: perhaps a complete worked example (including a DTD).
: Keep up the good work!
: Many thanks,
: Ian Brettell,
: Indus International.
Thanks for the input. I will pass it onto the documentation team.
Oracle XML Team
http://technet.oracle.com
Oracle Technology Network
null -
How can I parse an XML string, (not an XML file)?
Hi,
I am using Xerces2 Java Parser 2.4.0,
I wanta parse an XML string, not an XML file, but
in the Parser class there is only following methods:
parse(InputSource source)
parse(java.lang.String systemId)
thankshi
InputSource is = new InputSource(new ByteArrayInputStream(xmlSrc.getBytes()));
HTH
vasanth-ct -
I need some help to parse an XML String instead of an XML file. The string can be like.
String myRecords =
"<data>"+
" <employee>"+
" <name>John</name>"+
" <Designation>Manager</Designation>"+
" </employee>"+
" <employee>"+
" <name>Sara</name>"+
" <Designation>Clerk</Designation>"+
" </employee>"+
"<data>"+I tried it in a servlet, it and it worked. The entire code is long. But here it is most of it:
assuming that x is a string and has the xml of
<?xml version="1.0" ?>
- <company>
- <employee>
<firstname>Tom</firstname>
<lastname>Cat</lastname>
</employee>
- <employee>
<firstname>Paul</firstname>
<lastname>Enderson</lastname>
</employee>
- <employee>
<firstname>George</firstname>
<lastname>Jungle</lastname>
</employee>
</company>
=========================
try {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(*x*));
Document doc = db.parse(inStream);
doc.getDocumentElement().normalize();
out.println("Root element " + doc.getDocumentElement().getNodeName() + "<BR>");
NodeList nodeLst = doc.getElementsByTagName("employee");
out.println("Information of all employees<BR>");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
out.println("First Name : " + ((Node) fstNm.item(0)).getNodeValue() + "<BR>");
NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = lstNmElmnt.getChildNodes();
out.println("Last Name : " + ((Node) lstNm.item(0)).getNodeValue() + "<BR>");
} catch (Exception e) {
System.out.println(e);
out.close();
==============
The output is
Root element company
Information of all employees
First Name : Tom
Last Name : Cat
First Name : Paul
Last Name : Enderson
First Name : George
Last Name : Jungle -
Problem in parsing a xml string using dom parser
i want to parse a Xml String using a Dom parser......the parse function in dom parser takes only input stream as argument.......so i made the code as
InputStream inputstream = new StringBufferInputStream(XmlData) ;
InputSource inputSource = new InputSource(inputstream );
but saxexception is coming and also warning called
"java.io.StringBufferInputStream in java.io has been deprecated"
please help me.........i want to parse a Xml String using a Dom
parser......the parse function in dom parser takes
only input stream as argument.......This is not true of the DOM parser in Java 1.4. So you might want to get rid of your old parser and replace it by something more current. Or perhaps you are using 1.4 and you just didn't read all of the API docs. -
Hi All,
Can you please let me know for any sample code in xslt/java mapping for converting XML string into XML. We use SAP Pi 7.0
My XML string starts like this
<?xml version="1.0" encoding="UTF-8" ?>
- <ns0:MT_ReceiverFileStructure <namespace>"><Output><?xml version="1.0" encoding="ISO-8859-9"?><?xml-stylesheet type="text/xsl" href="<xsl>"?><Tarih_Date Tarih="11.09.2014" Date="09/11/2014>
Thanks,
PavithraThanks Praveen. It worked.
However, the xml i have is an extract from a exchange rate URL and it has the reference to a xsl in it as below
<?xml version="1.0" encoding="ISO-8859-9"?><?xml-stylesheet type="text/xsl" href="<ABC.xsl>"?>.
So there is an error in sxmb_moni. Is it possible to remove this. -
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. -
Convert XML string into an abap format date and time
Hi,
Does anyone know of a method or a function module in ABAP which converts XML string into an abap format date and time.
Here is a part of the xml that I want to convert.
<ns2:EventDateTime>2009-07-02T10:13:45+10:00</ns2:EventDateTime>
<ns2:EventMessageTransmissionDateTime>2009-07-02T10:13:45.987+10:00</ns2:EventMessageTransmissionDateTime>
Currently EventDateTime and EventMessageTransmissionDateTime are type XSDDATETIME_Z and these are converted to proper dates and times. We will be changing these fields to a STRING instead of XSDDATETIME_Z. The reason for this is to make the field more versatile. The customer would be receiving dates with Zulu (2009-09-23T12:00:00Z), with offsets (2009-09-23T12:00:00+10:00/-10:00) and just local timestamp (2009-09-23T12:00:00). With this, we need to make the date fields as string
to be able to accept the various date formats (esp. the local timestamp).
I am looking for a standard function module or method that will convert the xml string to a proper date and time abap format.
Would appreciate anyone's help!
Thanks.
Edited by: eunice ocson on Jul 13, 2009 1:49 AM
Edited by: eunice ocson on Jul 13, 2009 1:50 AM
Edited by: eunice ocson on Jul 13, 2009 1:51 AM
Edited by: eunice ocson on Jul 13, 2009 1:51 AMHi Eunice
Use the FM 'SMUM_XML_PARSE'
for more info
[Convert XML string to ABAP|XML String to ABAP or GUI]
hope it helps you.
Thanks!! -
Help: How to parse XML string into Node Context
Hi Experts,
I am trying to work with a web dynpro for java application which calls a Web Service. I can call the web service successfully, however I have a problem on interpreting the response result into table. The response result is in (XML) string format, like this:
I followed this , but it resulted to an error:
com.sap.engine.lib.xml.parser.NestedSAXParserException: Fatal Error: com.sap.engine.lib.xml.parser.ParserException: Name expected: 0x20(:main:, row:158, col:59)(:main:, row=158, col=59) -> com.sap.engine.lib.xml.parser.ParserException: Name expected: 0x20(:main:, row:158, col:59)
do anyone of you had a similar experience and were able to resolve it, please post it here. it will be highly appreciated. thanks in advance.Try this :
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new org.xml.sax.InputSource(new StringReader(strXml)));Hope this helps. -
How to parse whole xml elements into a java String
hello everybody,
I am trying to parse whole xml into a string for example
my xml file is as below:
<root>
<element>
<data id="1">1</data>
</element>
<element>
<data id="2">2</data>
</element>
</root>
in java whole data should be transfered as
String xmlString ="<root><element><data id=\"1\">1</data></element><element><data id=\"2\">2</data></element></root>";or in a simple way can xml be copied into a string? any assistance ...
thanQ in Advance.
Han.This code is to convert xml document to a string.
try {
javax.xml.transform.TransformerFactory tfactory = TransformerFactory.newInstance();
javax.xml.transform.Transformer xform = tfactory.newTransformer();
javax.xml.transform.Source src = new DOMSource(xmlString);
java.io.StringWriter writer = new StringWriter();
StreamResult result = new javax.xml.transform.stream.StreamResult(writer);
xform.transform(src, result);
//System.out.println(writer.toString());
} catch (TransformerConfigurationException e) {
e.printStackTrace();
}catch(Exception ex )
ex.printStackTrace();
} -
Insert XML String into XML file at a certain position
Hello,
I have this xml string:
<jdbc-driver-params>
<url>jdbc:oracle:thin:@localhost:1521:mydb</url>
<driver-name>oracle.jdbc.OracleDriver</driver-name>
<properties>
<property>
<name>user</name>
<value>myuser</value>
</property>
</properties>
<password-encrypted>myuser</password-encrypted>
</jdbc-driver-params>and i need to insert it into an xml file at a certain position (as child for a node)
The xml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<jdbc-data-source xmlns="http://www.bea.com/ns/weblogic/90"
xmlns:sec="http://www.bea.com/ns/weblogic/90/security"
xmlns:wls="http://www.bea.com/ns/weblogic/90/security/wls"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/920 http://www.bea.com/ns/weblogic/920.xsd">
<name>myDB</name>
<jdbc-data-source-params>
<global-transactions-protocol>OnePhaseCommit</global-transactions-protocol>
</jdbc-data-source-params>
</jdbc-data-source>And this is how I would like to get it in the end:
<?xml version='1.0' encoding='UTF-8'?>
<jdbc-data-source xmlns="http://www.bea.com/ns/weblogic/90" xmlns:sec="http://www.bea.com/ns/weblogic/90/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wls="http://www.bea.com/ns/weblogic/90/security/wls" xsi:schemaLocation="http://www.bea.com/ns/weblogic/920 http://www.bea.com/ns/weblogic/920.xsd">
<name>mydb</name>
<jdbc-driver-params>
<url>jdbc:oracle:thin:@localhost:1521:myDB</url>
<driver-name>oracle.jdbc.OracleDriver</driver-name>
<properties>
<property>
<name>user</name>
<value>myuser</value>
</property>
</properties>
<password-encrypted>myuser</password-encrypted>
</jdbc-driver-params>
<jdbc-connection-pool-params>
<test-table-name>SQL SELECT 1 FROM DUAL</test-table-name>
</jdbc-connection-pool-params>
<jdbc-data-source-params>
<global-transactions-protocol>OnePhaseCommit</global-transactions-protocol>
</jdbc-data-source-params>
</jdbc-data-source>So, I obtain the node for the given xml string, the jdbc-data-source node from the xml file and i attempt the appendChild. The problem is that nothing really gets inserted into the xml file.
Someone, any idea?
My code:
try
DOMParser parser = new DOMParser();
parser.parse(xmlFileName);
Document doc = parser.getDocument(); // the document we will insert node into
Node root = doc.getElementsByTagName("jdbc-data-source").item(0);
//get XML string node
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlString));
Document doc4XMLString = db.parse(inStream);
Node rootXMLString = doc4XMLString.getElementsByTagName("jdbc-driver-params").item(0);
root.appendChild(doc.importNode(rootXMLString, true));
return true;
catch (Exception e)
e.printStackTrace();
}Thanks,
johnny
Edited by: smeag0l on Aug 6, 2008 5:08 PM
Edited by: smeag0l on Aug 6, 2008 5:43 PMWell, you helped me again :-) Thank you very much!
Here is how the code should look:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db4XMLFile = factory.newDocumentBuilder();
Document doc4XMLFile = db4XMLFile.parse(xmlFileName);
Node root4XMLFile = doc4XMLFile.getElementsByTagName(rootNodeName).item(0);
DocumentBuilder db4XMLString = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlString));
Document doc4XMLString = db4XMLString.parse(inStream);
Node root4XMLString = doc4XMLString.getElementsByTagName(xmlStringNodeName).item(0);
root4XMLFile.appendChild(doc4XMLFile.importNode(root4XMLString, true));
File file = new File(xmlFileName);
Result result = new StreamResult(file.toURI().getPath());
Source source = new DOMSource(doc4XMLFile);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
Maybe you are looking for
-
Powermac G5 will not boot after 10.5.6 install
I recently inherited a Powermac G5 with 8gb ram(recognizes 6) 2x150gb HD which was at 10.5.8 HD1 was 10.5.8 HD2 is setup as backup most apps would not launch so decided to refresh and start over by erasing and installing anew 10.5.6 and going from th
-
hi there could anyone help me with with this small issue since i update something to do with my network when i try to log on to the internet useing my default settings in my home wireless network, it goes straight onto virgin network is there any way
-
Displaying php webpage in Jeditorpane
hello I want to open a php webpage in java. I tried using JEditorPane but I figured out that it only works for html. Is there any other option to open a php or any other scripting webpage in java application Ritesh
-
How do I get access to an AdvancedDataGridRendererProvider?
In the snippet of the following code: <mx:rendererProviders> <mx:AdvancedDataGridRendererProvider depth="2" column="{protocolID}" columnSpan="1" renderer="ProtocolComboBox"/> </mx:rendererProviders> Can someone tell me how to get access to the Protoc
-
Working with CS5 for a few weeks now with no problems. Suddenly today Illustrator doesn't want to open any files. Keeps giving me the message "Unable to set maximum number of files to be opened." Trashed prefs but that made no difference. Anyone know