How to Parse an XML string

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

Similar Messages

  • 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)
    thanks

    hi
      InputSource is = new InputSource(new ByteArrayInputStream(xmlSrc.getBytes()));
      HTH
    vasanth-ct

  • Parsing an XML string

    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.
    null

    Ian 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 to parse a XML file

    I am a new learner to XML & JAVA,I dont't know how to parse the XML file using JAXP,Who can tell me,Who can write an Example?
    thx
    Best Regards.

    Using the SAXParser in JAXP the parsing of the XML file is event driven.
    Instantiate the parser:
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    InputSource is = new InputSource(new FileReader(theXML));call the parse method:
    parser.parse(is, this);The following events are fired as the parser works through the XML public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws org.xml.sax.SAXException
    public void endElement(String namespaceURI, String localName, String qName) throws org.xml.sax.SAXException
    characters(char[] ch, int start, int length)etc.
    You write what you want within each of these sections to handle the structure of your data. Keep in mind SAX is useful only when you know the structure of your XML.

  • How to get an XML string store in CLOB or LONG column ?

    How to get an XML string store in CLOB or LONG column ?
    We use XSU with the following command
    String str = qry.getXMLString();
    but all the "<" are replace by "&lt;"
    It's impossible to parse the result for XSLT transformation
    Thank's for your help
    Denis Calvayrac
    Example :
    in the column "TT_NAME"
    "<name><firstname>aaa</<firstname><lastname>bbb</lastname></name>
    I want this result
    <TT_NAME>
    <name>
    <firstname>aaa</firstname>
    <lastname>bbb</lastname>
    </name>
    </TT_NAME>
    but, I have this result
    <TT_NAME>
    &lt;name&gt;
    &lt;firstname&gt;aaa&lt;/firstname&gt;
    &lt;lastname&gt;bbb&lt;/lastname&gt;
    &lt;/name&gt;
    </TT_NAME>

    Can you post some of your code, so I can take a look ?
    Thanks

  • How to parse thus XML data?

    Hi,experts:
    In below thread:
    Receiving .Net dataset with deployed proxies
    i asked how to create a external definition in IR base on above XML data.
    Now,i have created a XSD file base on the XML data.And importing it into IR successfully.
    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:Locale="zh-CN">
    <xs:complexType>
    <xs:choice maxOccurs="unbounded">
    <xs:element name="Status">
    <xs:complexType>
    <xs:attribute name="Result" type="xs:string"/>
    </xs:complexType>
    </xs:element>
    </xs:choice>
    </xs:complexType>
    </xs:element>
    </xs:schema>
    And now,the question is how to parse the XML data in diffgr:diffgram  segment.It seems a MS-XML syntax.Can it be parsed by XI?
    I tried,but the following error occurs:
    com.sap.aii.utilxi.misc.api.BaseRuntimeException: RuntimeException in Message-Mapping transformation: Cannot produce target element /ns0:ZMT_SD_ORDER01_RESULT. Check xml instance is valid for source xsd and target-field mapping fulfills requirements of target xsd at com.sap.aii.mappingtool.tf3.AMappingProgram.start

    Hi,
    The above Exception seems to be because of mapping error.
    Check your mapping for all the mandatory 1-1 mapping, also the 1-unbounded parent node mapping.
    Once when you import the XSD and activate your External Definition if it does without any error then there is no problem with your External Definition.
    If this error occurs only when you test your mapping then this is mapping error and not because of XSD.
    Please check the parent node mapping like 1-unbounded.
    Reward Points if useful
    Regards
    Ashmi.

  • 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>

  • 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.

  • How to append an xml string as a child node to a dom document

    Hi
    I have an xml represented as a String. Now I want to add this xml string as a child node to another DOM Document.
    Do I have to first parse the xml String into a xml Document and then add the nodes to the existing Document. Is there a simpler way to do this. Any input is appreciated.
    Many thanks in advance.

    radsat wrote:
    Hi
    I have an xml represented as a String. Now I want to add this xml string as a child node to another DOM Document.
    Do I have to first parse the xml String into a xml Document and then add the nodes to the existing Document. yes, this is what you need to do.
    Is there a simpler way to do this. Any input is appreciated.no, there really isn't, sorry.

  • How quickly parse big XML file (60 MB) ???

    How quickly parse big XML file (60 MB) ???

    I assume you mean load it into XML DB ?. Fundamentally your document is about the upper limit for 9.2.x. I would strongly recommend trying to break it up into a set of smaller documents using a SAX parser before trying to load it into XML DB. In 10g it should be possible to load much bigger documents than this.

  • How to Parse the XML generated by Mapping LookUp - RFC API

    Hi Friends,
    I m using the link by Michal Krawczyk for Mapping Lookups - RFC API
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/a03e7b02-eea4-2910-089f-8214c6d1b439
    How to parse the XML created in the target node ?
    Regards
    Pravesh

    Hi,
    Check the second half of my code in this blog,
    /people/bhavesh.kantilal/blog/2006/11/20/webservice-calls-from-a-user-defined-function
    It deals with webservice call's but almost the same for RFC.
    Regards
    Bhavesh

  • How to parse nested xml file using dom

    i want to parse nested xml file
    please tell me how to parse nested xml
    for eg.
    <xml>
    <row>
    <name>Rahul<name>
    <row><newXml>
    <newXML>
    <Row>
    <code>12</code>
    </Row>
    <newXML>
    <XML>
    please tell how to parse this file

    Normally if you have no idea about X, the first thing you should do is google "X tutorial". You will find plenty of them out there. And the advantage is, they are better written than whatever we spend two minutes throwing together here. Not to mention that it saves us the two minutes.
    But if you have specific questions with your SAX parser when you get it going, then ask them here. Actually, ask them in the XML forum here, not this one.

  • 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();
                             }

  • Parse an XML String

    hi lets say i got an XML String which looks like this..
    String xmlstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><GET_REALIZED_GAIN_LOSS_DETAIL_RESPONSE xsi:schemaLocation=\"http://www.statementone.com/webservice/schemas D:\\PMTSchema.xsd\" xmlns=\"http://www.statementone.com/webservice/schemas\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><STATUS>true</STATUS><ERRORS><ERROR><TYPE>String</TYPE><MESSAGE>String</MESSAGE><ERROR_ID>1</ERROR_ID></ERROR><ERROR><TYPE>String</TYPE><MESSAGE>String</MESSAGE><ERROR_ID>1</ERROR_ID></ERROR></ERRORS><GET_REALIZED_GAIN_LOSS_RESULT><XYZ>String</XYZ></GET_REALIZED_GAIN_LOSS_RESULT></GET_REALIZED_GAIN_LOSS_DETAIL_RESPONSE>";
    DocumentBuilderFactory factory =
    DocumentBuilderFactory.newInstance();
    DocumentBuilder db = factory.newDocumentBuilder();
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(xmlstring));
    Document doc1 = db.parse(inStream);
    I notice that all the values i set in XML are available in the doc1 field. But I was not able to get them as a string..
    Can Some one tell me how to get the attributes out of the doc1? I tried getElementBytag and other options.. Do i need to take out the tag items in the sequence in which they are given? or can i select a tag random and pick up the attributes??
    Plzz help me out!!

    Hope this helps you, let me know.
    String xmlstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>.......  </GET_REALIZED_GAIN_LOSS_DETAIL_RESPONSE>";
         DocumentBuilderFactory factory =
         DocumentBuilderFactory.newInstance();
         DocumentBuilder db = factory.newDocumentBuilder();
         InputSource inStream = new InputSource();
         inStream.setCharacterStream(new StringReader(xmlstring));
         Document doc1 = db.parse(inStream);
       NamedNodeMap attribes = doc1.getAttributes();
       NodeList nodes = doc1.getChildNodes();http://snippets.dzone.com/posts/show/3575
    http://www.brics.dk/~amoeller/XML/programming/domexample.html
    Message was edited by:
    Srini_Kandula

  • 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.

Maybe you are looking for

  • ITunes user library transfer from one account to another on the SAME comptr

    Initial information: I have my computer, internet is with SBC Yahoo DSL. It has five sub accounts on it; mine, my wife's and my three children. Each has their own subaccount to make life easy. I bought my wife an ipod in the August and through ignora

  • Help with creating a custom table cell editor?

    hi, i was reading up on various tutorials and trying to write codes that pops up a simple calendar when clicked on text of the Date class in a table, so far, i can't seem to get my classes working.. the following is some classes i've written for this

  • -lresolv not found

    hi, I encountered a problem while compiling cryptcat on solaris 8, ultra 5. error: ld: fatal: library -lresolv: not found Things that I tried: 1) within the makefile, i had specify the options -L/lib -L/usr/lib/ 2) set and export $LD_LIBRARY_PATH, bu

  • Remote site transfer

    I have my website set up with about 100 files at a remote LV site. I wish to transfer every one of those files into my new remote CX site. HOW without copying all to local then sending to remote?

  • New to Java, where do I start??!?!

    Hello everyone, let me just introduce myself. My name is Jeff and I am from PA, I am a recent graduate of Penn State university with a bachelors of science in information science and technology, application/integration. My major dealt with alot of an