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

Similar Messages

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

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

  • 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

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

  • Getting Error while creating Document object  after  parsing XML String

    Hi All,
    I have been trying to parse an XML string using the StringReader and InputSource interface but when I am trying to create Document Object using Parse() method getting error like
    [Fatal Error] :2:6: The processing instruction target matching "[xX][mM][lL]" is not allowed.
    seorg.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.
    Please find the code below which i have been experimenting with:
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.StringReader;
    import java.util.List;
    import java.util.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import java.io.*;
    public class TestMain {
         public static void main(String[] args) {
              String file = "";
              file = loadFileContent("C:\\Test.xml");
              System.out.println("contents >> "+file);
              parseQuickLinksFileContent(file);
    public static void parseQuickLinksFileContent(String fileContents) {
    PWMQuickLinksModelVO objPWMQuickLinksModelVO = new PWMQuickLinksModelVO();
         try {
    DocumentBuilderFactory factory =           DocumentBuilderFactory.newInstance();
         DocumentBuilder builder = factory.newDocumentBuilder();
         StringReader objRd = new StringReader(fileContents);
         InputSource objIs = new InputSource(objRd);
         Document document = builder.parse(objIs); // HERE I am getting Error.
         System.out.println(document.toString());
    What is happening while I am using builder.parse() method ???
    Thanks,
    Rajendra.

    Getting following error
    [Fatal Error] :2:6: The processing instruction target matching "[xX][mM][lL]" is not allowed.
    seorg.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.

  • XML string to XML parsing in JCD

    I have stored an XML file as a CLOB in the Oracle DB. While fetching this data into JCD using Oracle OTD, I am getting this CLOB field as a string containing the XML. Now I want to parse this XML string to XML, as I need to map the individual fields to an XSD OTD, which will be my output.
    Kindly suggest a way to achieve this.

    An XSD OTD has an unmarshalFromString() method:
    inputFormat.unmarshalFromString( strData );
    When putting the XML into the CLOB it could be a good idea to wrap an outputstream into a Writer object in order to make certain that the encoding is correct, depending how the data is represented. When retrieving CLOB data using getCharacterStream() you will get a Reader object where the encoding is already given.

  • How to parse XML string fetched from the database

    i want to parse the XML string which is fetched from the oracle database.
    i have inserted the string in xml format in the database. The type of the field in which it is inserted is varchart2.
    I am successfully getting it using jdbc, storing it in a String.
    Now it is appended with xml version 1.0 and string is ready for parsing.
    Now i am making following programming.
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = Builder.parse(xmlString);
    Element root = doc.getDocumentElement();
    NodeList node = root.getElementsByTagName("product");
    But i am getting IOException at the statement
    Document doc = Builder.parse(xmlString);
    there fore i request u to kindly help me in solving this error.
    -regards
    pujan

    DocumentBuilder does not have a method parse with xml string as aparameter. The string should be a xml document uri.
    Convert xml string to StringReader.
    parse(new InputSource(new StringReader(xmlString)));

  • JDOM: Parsing XML String, getting error

    Hello,
    I am new to this forum, so please forgive me
    if this has already been asked before. I want to
    parse an XML string. I know the JDOM parser works
    great with a file, but apparently I have been
    unsuccessful parsing an XML String. Below is how I
    initialize the parser:
    import java.io.*; //Import proper packages
    import org.jdom.*;
    import org.jdom.input.*;
    import org.jdom.output.*;
    import java.util.*;
    import java.lang.*;
    public class XMLParser{
    private Document doc = null;
    public XMLParser(String xml){
    doc = readDocument(xml);
    private Document readDocument(String xml) {
    try {
    SAXBuilder builder = new SAXBuilder();
    org.jdom.Document result = builder.build(new
    StringReader(xml));
    return result;
    } catch(JDOMException e) {
    e.printStackTrace();
    } catch(NullPointerException e) {
    e.printStackTrace();
    return null;
    } //readDocument
    The following is the error I receive:
    JDOM/xmlparser.java [81:1] cannot resolve symbol
    symbol : method build (java.io.StringReader)
    location: class org.jdom.input.SAXBuilder
    org.jdom.Document result = builder.build(new
    StringReader(filename));
    --> Arrow pointing to builder.build
    Please if someone can help me out. If JDOM does not
    have this feature, then can someone please recommend a
    parser that can parse an XML String.

    Thank you for your help, although it seems like it was JDom 9 beta. When I tried with JDOM 8 beta, everything worked fine even with the StringReader. So if anyone is having similar problems with JDom 9 then try with JDom 8.

  • XML string parsing

    Is there any class method to parse an XML string into tags and contents?
    I have a response in XML and would like to read a tags contents.
    Thanks

    Hi KP,
    look at the iXML library. http://help.sap.com/saphelp_nw04/helpdata/en/47/b5413acdb62f70e10000000a114084/frameset.htm
    Depending what release you are developing on you might also want to look at SImple Transformations.
    Cheers
    Graham

  • Parsing XML string with XPath

    Hi,-
    I am trying to parse an XML string with xpath as follows but I am getting null for getresult.
    I am getting java.xml.xpath.xpathexpressionexception at line where
    getresult = xpathexpression.evaluate(isource); is executed.
    What should I do after
    xpathexpression = xPath.compile("a/b");in the below snippet?
    Thanks
    String xmlstring ="..."; // a valid XML string;
    Xpath xpath = XPathFactory.newInstance().newPath();
    xpathexpression = xPath.compile("a/b");
    // I guess the following line is not correct
    InputSource isource = new inputSource(new ByteArrayInputStream(xmlstring.getBytes())); right
    getresult = xpathexpression.evaluate(isource);My xml string is like:
    <a>
      <b>
         <result> valid some more tags here
         </result>
      </b>
      <c> 10
      </c>
    </a>Edited by: geoman on Dec 8, 2008 2:30 PM

    I've never used the version of evaluate that takes an InputSource. The difficulty with using it is that it does not save the DOM object. Each expression you evaluate will have to create the DOM object, use it once and then throw it away. I've yet to write a program that only needs one answer from an XML document. Usually, I use XPath to locate somewhere in a document and then read "nearby" content, add new content nearby, delete content, or move content. I'd suggest you may want to parse the XML stream and save the DOM Document.
    Second, all of the XPath expressions search from a "context node". I have not had good luck searching from the Document object, so I always get the root element first. I think the expression should work if you use the root as the context node. You will need one of the versions of evaluate that uses an Object as the parameter.

  • How to parse xml string

    Hi! I'm having problems parsing an xml string. I've done DOM and SAX parsing before. But both of them either parse a file or data from an input source. I don't think they handle strings. I also don't want to write the string into a file just so I can use DOM or SAX.
    I'm looking for something where I could simply do:
    Document doc = documentBuilder.parse( myXMLString );
    So the heirarchy is automatically established for me. Then I could just do
    Element elem = doc.getElement();
    String name = elem.getTagName();
    These aren't the only methods I would want to use. Again, my main problem is how to parse xml if it is stored in a string, not a file, nor comming from a stream.
    thanks!

    But both of them either parse a file or data from an input source. I don't think they handle strings.An InputSource can be constructed with a Reader as input. One useful subclass of Reader is StringReader, so you'd use something likeDocument doc = documentBuilder.parse(new InputSource(new StringReader(myXMLString)));

  • Parsing from a string of XML?

    Hi there,
    I'm using DOM to parse some XML. However, the XML is not in a file, it's in a String. So the DocumentBuilder's parse(...) method takes an InputStream or File object but I'm looking to parse a String. Can anybody help me??
    Cheers,
    Sean

    Ok I found out a way to parse an XML string:
    DocumentBuilder builder = factory.newDocumentBuilder();
    StringReader sr = new StringReader(xmlString.toString());
    InputSource is = new InputSource(sr);
    document = builder.parse(is);
    But I'm getting the following error on the parse() line:
    [Fatal Error] :1:20: A pseudo attribute name is expected.
    org.xml.sax.SAXParseException: A pseudo attribute name is expected.
         at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
         at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
         at test.TestDOM.main(TestDOM.java:61)
    The XML string is:
    String xmlString = "<?xml version=\"1.0\"><tag><tag_id>250397</tag_id><reader_id>1</reader_id><rssi>74</rssi><date>7/19/2006</date><time>2:59:47 PM</time></tag>";
    Can anybody help?
    Cheers,
    Sean

  • Parsing XML Strings

    I am getting an XML String from a web-service.. Is there a method inside of BPM to parse this xml string?

    Hi, my xml string is:-
    <?xml version="1.0" encoding="UTF-8" ?>
    <ns2:Exception xmlns:ns2="http://example.com/" >
         <errorCode>0</errorCode>
         <errorSubcode>0</errorSubcode>
         <message>Connection refused</message>
         <messageWithProperties>Connection refused
         Error Code=[0]
         ticketId=[1]
         fileName=[testFile]
    </messageWithProperties>
         <properties>
              <name>Error Code</name>
              <value>0</value>
         </properties>
         <properties>
              <name>ticketId</name>
              <value>1</value>
         </properties>
         <properties>
              <name>fileName</name>
              <value>testFile</value>
         </properties>
         <propertiesAsString>     Error Code=[0]
         ticketId=[1]
         fileName=[testFile]
    </propertiesAsString>
    </ns2:Exception>
    I wanted to parse through it and get the errorCode....
    I am using :-
    xmlObject.load(xmlText : xmlContent);
    xmlMessage = xmlObject.selectString(xpath : "/ns2/errorCode");
    But this doesn't seem to work..
    Any idea?

Maybe you are looking for

  • How to make one file?

    I have basically 2 problems here a)When I do generate a signature using the enduser's privatekey,,I will be ending up with two files one signature file and other the original document,,I need one file which contains the signature as well as the origi

  • I can't sign in to FaceTime keeps sayin check network connections but my network is fine

    im havin trouble signin into facetime on my mac and i cant get my head around it ive my ID setup but everytime i click on sign in it keeps coming up with CHEAK YOUR NETWORK CONNECTIONS AND TRY AGAIN. There is nothing wrong with my connections as im r

  • Download Flex hero SDK ASDOCS

    Hi, Where can I download the asdocs? The SDk contains a small directory asdocs with a build.xml. I tried to build it, but get: 4.5.0\asdoc\build.xml:47: FLEX_HOME must be set to use the Flex Ant Tasks (I have set FLEX_HOME) The online help is no long

  • Replacing CR and LF

    How does on remove the CR and LF from a String obtained by a JTextArea.getText() call? I just want to replace them with spaces. I tried: mString.replace( '\n', ' ' ); mString.replace( '\r', ' ' ); but it had no effect... Thanks, Bill

  • Why are my "Clip, Fade to" grayed out?

    I'm new to iMovie (from Windows Movie Maker) and just playing around.  I've created a project and I'm trying to use the "Fade to" options.  But when I choose "Clip, Fade to" the options are grayed out.