Parse XML from string.

I have writen simple fuction which have one parameter of String type. In this parameter i am sending an XML string. Is there anyone who knows how to parse this XML-String ?
Thanks.

parse(new StringReader(theString));

Similar Messages

  • Xerces - Parse XML from String

    I am trying to parse an xml string using Xerces.
    I have the following code:
    String xml = <segments meters="8643" seconds="538" distance="5.4 mi" time="8 mins"><segment id="seg0"  pointIndex="0" meters="122" seconds="11"  distance="0.1 mi"  time="11 secs">Head  <b>southwest</b> from <b>B Ave NE</b>
    </segment>
    <segment id="seg1" pointIndex="2" meters="239" seconds="22" distance="0.1 mi" time="21 secs">Turn <b>left</b> at <b>19th St NE</b></segment>
    <segment id="seg2" pointIndex="5" meters="2985" seconds="192" distance="1.9 mi" time="3 mins">Turn <b>right</b> at <b>1st Ave NE</b></segment>
    <segment id="seg3" pointIndex="43" meters="3280" seconds="211" distance="2.0 mi" time="3 mins">Continue on <b>1st Ave SW/1st Ave NW</b></segment>
    <segment id="seg4" pointIndex="96" meters="158" seconds="10" distance="0.1 mi" time="10 secs">Bear <b>right</b> at <b>US-151-BR S</b></segment>
    <segment id="seg5" pointIndex="102" meters="1859" seconds="93" distance="1.2 mi" time="1 min">Turn <b>right</b> at <b>16th Ave SW</b></segment>;
    XMLReader reader = new SAXParser();
    reader.setContentHandler(new Handler());
    reader.parse(xml);I am getting the followoing error:
    org.xml.sax.SAXParseException: File "<segments meters="8643" seconds="538" distance="5.4 mi" time="8 mins"><segment id="seg0" pointIndex="0" meters="122" seconds="11" distance="0.1 mi" time="11 secs">Head  <b>southwest</b> from <b>B Ave NE</b></segment><segment id="seg1" pointIndex="2" meters="239" seconds="22" distance="0.1 mi" time="21 secs">Turn <b>left</b> at <b>19th St NE</b></segment><segment id="seg2" pointIndex="5" meters="2985" seconds="192" distance="1.9 mi" time="3 mins">Turn <b>right</b> at <b>1st Ave NE</b></segment><segment id="seg3" pointIndex="43" meters="3280" seconds="211" distance="2.0 mi" time="3 mins">Continue on <b>1st Ave SW/1st Ave NW</b></segment><segment id="seg4" pointIndex="96" meters="158" seconds="10" distance="0.1 mi" time="10 secs">Bear <b>right</b> at <b>US-151-BR S</b></segment><segment id="seg5" pointIndex="102" meters="1859" seconds="93" distance="1.2 mi" time="1 min">Turn <b>right</b> at <b>16th Ave SW</b></segment></segments>" not found.
         at org.apache.xerces.framework.XMLParser.reportError(XMLParser.java:1219)
         at org.apache.xerces.readers.DefaultEntityHandler.startReadingFromDocument(DefaultEntityHandler.java:501)
         at org.apache.xerces.framework.XMLParser.parseSomeSetup(XMLParser.java:314)
         at org.apache.xerces.framework.XMLParser.parse(XMLParser.java:1097)
         at org.apache.xerces.framework.XMLParser.parse(XMLParser.java:1139)
         at com.shiftyeyes.xmlTest.main(xmlTest.java:34)
    Exception in thread "main" anyone know how I can fix this? Thanks!!

    reader.parse(new InputSource(new StringReader(xml)));

  • How to Parse XML into String in BPEL?

    Hi,
    Can anyone tell me, how can I parse XML into String?
    I am taking input from File Adapter, File adapter is reading that XML.
    Then in assign activity i am using XPath expression(built functions) using XMLParser(),doTranslateToNative() etc.. many functions I have tried but XML is not getting parsed into String Variable.
    Please help me asap.
    Thanks
    Shikha

    Thanks a lot Eric.
    I am trying this, oraext:get-content-as-string('receiveInput_Read_InputVariable','body','/ns3:orders')
    but getting this error
    <bpelFault><faultType>0</faultType><subLanguageExecutionFault xmlns="http://schemas.oracle.com/bpel/extension"><part name="summary"><summary>XPath expression failed to execute. An error occurs while processing the XPath expression; the expression is oraext:get-content-as-string('receiveInput_Read_InputVariable','body','/ns3:orders'). The XPath expression failed to execute; the reason was: internal xpath error. Check the detailed root cause described in the exception message text and verify that the XPath query is correct. </summary></part><part name="code"><code>XPathExecutionError</code></part></subLanguageExecutionFault></bpelFault>

  • Parsing XML from Socket input stream

    I create a sax parser to which I send the InputStream from the socket
    But my HandlerBase never gets the events. I get startDocument
    but that is it, I never get any other event.
    The code I have works just like expected when I make the InputStream
    come from a file. The only differeence I see is that when I file is used the
    InputStream is fully consumed while with the socket the InputStream
    is kept open (I MUST KEEP THE SOCKET OPEN ALL THE TIME). If the parser
    does not generate the events unless the InputStream is fully consumed,
    isn't that against the whole idea of SAX (sax event driven) .
    Has anyone been succesfull parsing XML from the InputStream of a socket?
    if yes how?
    I am using JAXP 1.0.1 but I can upgrade to JAXP 1.1.0
    which uses SAX 2.0
    Does anybody know if my needs can be met by JAXP 1.1.0?
    Thanks

    I did the same with client/server model.
    I have client program with SAX parser. Please try if you can make the server side. I was be able to write the program with help from this forum. Please search to see if you can get the forum from which I got help for this program.
    // JAXP packages
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    // JAVA packages
    import java.util.*;
    import java.io.*;
    import java.net.*;
    public class XMLSocketClient {
    final private static int buffSize = 1024*10;
    final private static int PORTNUM = 8888;
         final private static int threadSleepValue = 1000;
    private static void usage() {
    System.err.println("Usage: XMLSocketClient [-v] serverAddr");
    System.err.println(" -v = validation");
    System.exit(1);
    public static void main(String[] args) {
    String address = null;
    boolean validation = false;
    Socket socket = null;
    InputStreamReader isr_socket = null;
    BufferedReader br_socket = null;
    CharArrayReader car = null;
    BufferedReader br_car = null;
    char[] charBuff = new char[buffSize];
    int in_buff = 0;
    * Parse arguments of command options
    for (int i = 0; i < args.length; i++) {
    if (args.equals("-v")) {
    validation = true;
    } else {
    address = args[i];
    // Must be last arg
    if (i != args.length - 1) {
    usage();
    // Initialize the socket and streams
    try {
    socket = new Socket(address, PORTNUM);
    isr_socket = new InputStreamReader(socket.getInputStream());
    br_socket = new BufferedReader(isr_socket, buffSize);
    catch (IOException e) {
    System.err.println("Exception: couldn't create stream socket "
    + e.getMessage());
    System.exit(1);
    * Check whether the buffer has input.
    try {
    while (br_socket.ready() != true) {
                   try {
                        Thread.currentThread().sleep(threadSleepValue);     
                   catch (InterruptedException ie) {
              System.err.println("Interrupted error for sleep: "+ ie.getMessage());
                   System.exit(1);
    catch (IOException e) {
    System.err.println("I/O error for in.read(): "+ e.getMessage());
    System.exit(1);
    try {
    in_buff = br_socket.read(charBuff, 0, buffSize);
    System.out.println("in_buff = " + in_buff);
    System.out.println("charBuff length: " + charBuff.length);
    if (in_buff != -1) {
    System.out.println("End of file");
    } catch (IOException e) {
    System.out.println("Exception: " + e.getMessage());
    System.exit(1);
    System.out.println("reading XML file:");
    StringBuffer display = new StringBuffer();
    display.append(charBuff, 0, in_buff);
    System.out.println(display.toString());
    * Create BufferedReader from the charBuff
    * in order to put into XML parser.
    car = new CharArrayReader(charBuff, 0, in_buff); // these two lines have to be here.
    br_car = new BufferedReader(car);
    * Create a JAXP SAXParserFactory and configure it
    * This section is standard handling of XML document by SAX XML parser.
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setValidating(validation);
    XMLReader xmlReader = null;
    try {
    // Create a JAXP SAXParser
    SAXParser saxParser = spf.newSAXParser();
    // Get the encapsulated SAX XMLReader
    xmlReader = saxParser.getXMLReader();
    } catch (Exception ex) {
    System.err.println(ex);
    System.exit(1);
    // Set the ContentHandler of the XMLReader
    xmlReader.setContentHandler(new MyXMLHandler());
    // Set an ErrorHandler before parsing
    xmlReader.setErrorHandler(new MyErrorHandler(System.err));
    try {
    * Tell the XMLReader to parse the XML document
    xmlReader.parse(new InputSource(br_car));
    } catch (SAXException se) {
    System.err.println(se.getMessage());
    System.exit(1);
    } catch (IOException ioe) {
    System.err.println(ioe);
    System.exit(1);
    * Clearance of i/o functions after parsing.
    try {
    br_socket.close();
    } catch (IOException e) {
    System.out.println("Exception: " + e.getMessage());
    try {
    socket.close();
    } catch (IOException e) {
    System.out.println("Exception: " + e.getMessage());
    try {
    br_car.close();
    } catch (IOException e) {
    System.out.println("Exception: " + e.getMessage());
    * The XML handler used by this program
    class MyXMLHandler extends DefaultHandler {
    // A Hashtable with tag names as keys and Integers as values
    private Hashtable tags;
    // Parser calls this once at the beginning of a document
    public void startDocument() throws SAXException {
    System.out.println("startDocument()");
    tags = new Hashtable();
    // Parser calls this for each element in a document
    public void startElement(String namespaceURI, String localName,
    String rawName, Attributes atts)
    throws SAXException
    String key = localName;
    Object value = tags.get(key);
    System.out.println("startElement()");
    System.out.println("namespaceURI: " + namespaceURI);
    System.out.println("localName: " + localName);
    System.out.println("rawName: " + rawName);
    if (value == null) {
    // Add a new entry
    tags.put(key, new Integer(1));
    } else {
    // Get the current count and increment it
    int count = ((Integer)value).intValue();
    count++;
    tags.put(key, new Integer(count));
    // Parser calls this once after parsing a document
    public void endDocument() throws SAXException {
    Enumeration e = tags.keys();
    System.out.println("endDocument()");
    while (e.hasMoreElements()) {
    String tag = (String)e.nextElement();
    int count = ((Integer)tags.get(tag)).intValue();
    System.out.println("Tag <" + tag + "> occurs " + count
    + " times");
    * Error handler of XML parser to report errors and warnings
    * This is standard handling.
    class MyErrorHandler implements ErrorHandler {
    /** Error handler output goes here */
    private PrintStream out;
    MyErrorHandler(PrintStream out) {
    this.out = out;
    * Returns a string describing parse exception details
    private String getParseExceptionInfo(SAXParseException spe) {
    String systemId = spe.getSystemId();
    if (systemId == null) {
    systemId = "null";
    String info = "URI=" + systemId +
    " Line=" + spe.getLineNumber() +
    ": " + spe.getMessage();
    return info;
    * The following methods are standard SAX ErrorHandler methods.
    * See SAX documentation for more info.
    public void warning(SAXParseException spe) throws SAXException {
    out.println("Warning: " + getParseExceptionInfo(spe));
    public void error(SAXParseException spe) throws SAXException {
    String message = "Error: " + getParseExceptionInfo(spe);
    throw new SAXException(message);
    public void fatalError(SAXParseException spe) throws SAXException {
    String message = "Fatal Error: " + getParseExceptionInfo(spe);
    throw new SAXException(message);

  • Can't parse xml from applet using dom on linux on Netscape 7 using jre 1.4.

    Hi,
    I can't seem to parse xml from an applet on linux on Netscape 7 using the JRE 1.4.
    My code looks like the following:
    StringBufferInputStream is = new StringBufferInputStream("<foo></foo>");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try
      builder = factory.newDocumentBuilder();
      domDocument = builder.parse(is); // this line creates an exception
    catch (Exception e)
      System.out.println(e);
    This code works fine from an applet on windows. On linux, the error message is:
    java.security.AccessControlException: access denied (java.util.PropertyPermission entityExpansionLimit read)
    I've tried both JRE 1.4.0_04 and 1.4.1_03
    Thanks!
    Q

    There's another posting about this same problem (platform unspecified), but the same error message. I was also having this problem (Windows 1.4.03) and swithced back to 1.4.01 and the problem went away. In the future, I may sign my applets to get a more generous security policy. But, I'm sure it'll be a lot of work (vs. a line of code somewhere).

  • Parse XML from CLOB field

    How can I parse XML from CLOB field? I need to replace or delete the node from XML document and update the database with new XML. I am using Oracle 9i release 2.
    Here is the XML. In this XML if section1 and section2 exists then I need to delete the section1 node. If section2 doesn't exist, replace section1 with section2 node.
    <Document ID='2' TypeID='2'>
    <Body>
    <Page Name='Page1'>
    <Sec ID='section1' Title='Section 1' GroupID='' />
    <Sec ID='section2' Title='Section 2' GroupID='' />
    </Page>
    </Body>
    </Document>
    Please help.. Thank you..

    In 9.2, you are limited into your options. Have a look into, among others, updateXML. Updating tp 10gR2 will give you more options to succeed.

  • Extracting the xml from string and parse it

    Hi all,
    I have a webservice, and calling one of the methods, returns xml data but store this data in a string.
    For example:
    String str = keysstub.getUserLMLArray(UserID,hash, Provider, Filter.ALL,TimeStampString).getXmlResults();returns <id>123456</id><id>123457</id><id>123458</id><id>123459</id><id>123461</id>and stores it in str.
    I have to take read this xml from the string and parse it accordingly to retreive the data from it.
    Please suggest how i can parse this xml from the string. it will be of great help. Code snippets from anyone would be of great help
    Thanks and Regards,
    Shikha

          * Get DOM document from a string containing valid XML.
          * @param string String to read XML content from.
         * @param varargs Optional arguments: 1: Validating?, 2: NamespaceAware?
          * @return DOM document or null if failed.
         * @throws Exception if failed.
         static public Document toDocument(String string, boolean... varargs) throws Exception {
            Document result = null;
            if (string != null) {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                if (varargs != null && varargs.length > 0) {
                    int count = varargs.length;
                    if (count > 0) {
                        factory.setValidating(varargs[0]);  //needs error handler
                    if (count > 1) {
                        factory.setNamespaceAware(varargs[1]);
                DocumentBuilder db = factory.newDocumentBuilder();
                result = db.parse(new InputSource(new StringReader(string)));
            }//else: input unavailable
            return result;
        }//toDocument()and don't forget that the string must be valid xml, so in your example the header is missing and the first element must embrace all subsequent elements, e.g.
    <?xml version="1.0"?>
    <ids>
    <id>123456</id><id>123457</id><id>123458</id><id>123459</id><id>123461</id>
    </ids>

  • Parsing XML from a session bean

    Hi,
    I am trying to use a Sax parser for parsing xml received from a back end
    legacy system. The code is executed from a Session bean.
    Debugging learned me that the parse() method on the parser hangs the
    container without any error or exception trace. The code works fine outside
    a container.
    All help will be highly appreciated.
    Kurt

    I found out that the InputStream implementation used parsing source inside
    the container is different
    then from the one outside (other type of VM of course!). The Weblogic
    implementation blocks at the end of
    the stream, while the normal SUN JDK 1.3 returns. This is not a bug, the bug
    I found is in my proxy that allows
    the connection to the backend. This proxy allows HTTP connections, and I
    parse the XML received over HTTP.
    Regards,
    Kurt
    "Todd Karakashian" <[email protected]> wrote in message
    news:[email protected]..
    That's seems odd. Perhaps there is something going on in your document
    handler code that triggers a hang in the environment of the server.
    When you see the hang, instruct the VM to give you a thread dump (type
    control-<break> on Windows, <control>-\ (backslash) on UNIX in the
    window in which the server is running; the results are dumped to
    stderr). That will show what every thread in the server is doing. If you
    email or post the thread dump, I will take a look at it and see if I can
    see what is going on. Also, let us know which platform, VM, parser, and
    WebLogic version you are using.
    Regards,
    -Todd
    Kurt Quirijnen wrote:
    Hi,
    I am trying to use a Sax parser for parsing xml received from a back end
    legacy system. The code is executed from a Session bean.
    Debugging learned me that the parse() method on the parser hangs the
    container without any error or exception trace. The code works fine
    outside
    a container.
    All help will be highly appreciated.
    Kurt--
    Todd Karakashian
    BEA Systems, Inc.
    [email protected]

  • How to use DOMParser from an Applet / Or, how to parse XML from an Applet?

    Hey,
    As stating in the subject line, I wonder how to do it without getting an �Access Denied� error.
    I would like to parse a XML file that has external DTD pointing to a SYSTEM location. Yes, I can change it to a public location. However, in either way, I have problems to use DOMBuilder to parse the xml file. The application always throws the security exception.
    I tried to use the DOMParser from org.apache.xerces.parsers to parse the xml file. I set the DOMParser to ignore parsing the external DTD, and use the DOMParser.parse(InputSource) to parse the xml file from a giving URL. However, I get null of the result document.
    Does anyone know how to parse the XML from an Applet? Or, does anyone know how to use the DOMParser from an Applet?
    Thank you very much,

    If the document resides on the local filesystem, you will need to sign a CAB or JAR for the applet to circumvent the sandbox's security restrictions. There are dozens of posts on how to do this. Basically, that will turn the applet into an application, from a Java security perspective.
    - Saish
    "My karma ran over your dogma." - Anon

  • Parsing xml from a socket stream

    Hi,
    I'm working on a client/server program, and I have the following problem. I'd like the client to send an xml-string to the server, and then the server to parse it (using SAX). The problem is, I cannot get the server to work.
    I thought the following would work, but it doesn't:
    InputSource xmlIn = new InputSource(socket.getInputStream());
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser xmlReader = factory.newSAXParser();     
    DefaultHandler handler = new MyHandler(); //          
    xmlReader.parse(xmlIn, handler);
    The setup now is, that the user of the client program can type something in the command line, press enter and the string is then sent to the server, which should parse it, but doesn't (instead gives a nullpointer exc.)
    Does anybody know how to parse an incoming string like this?
    thnx in advance,
    KS

    The parser expects to read to the end of the stream. If you closed the stream right after you wrote to it, I bet it would work. You wouldn't want to close the stream though would you? Try sending the string using a DataOuputStream and calling DataOutputStream.writeUTF(String) on the client side. Then, on the server side call String str = in.readUTF() (where 'in' is a DataInputStream). Then wrap the string in a StringReader and give the StringReader to the parser as it's input source.

  • Parse XML formatted String

    Hi All,
       I have a string field that is formatted in XML format. What I want to be able to do is pull a specific element from the xml formatted string.
    Example string:
    <customer><name>john</name><id>25636</id></customer>
    I want to retreive just the id number of 25636 from this string.
    I would I go about accomplishing this?
    Thank you in advance,

    I fixed it on my own.
    Here' s my answer for others that may need it:
    if(instr({field.xmlstring},'</id>')  - instr({field.xmlstring},'<id>') = 7)then
       mid(totext({field.xmlstring}),instr({field.xmlstring},'<id>')+4,3)
    else if(instr({field.xmlstring},'</id>')  - instr({field.xmlstring},'<id>') = 8)then
       mid(totext({field.xmlstring}),instr({field.xmlstring},'<id>')+4,4)
    else if(instr({field.xmlstring},'</id>')  - instr({field.xmlstring},'<id>') = 9)then
       mid(totext({field.xmlstring}),instr({field.xmlstring},'<id>')+4,5)
    I use the conditions to cover all possible lengths of the id number.

  • Parsing xml from forms6i,can anyone please help me

    Can anyone please help me.I need to parse a xml file from a directory.The parsing should help me in giving a structure for two things.
    1) i should be able to read the nodes( values between the tags) and display the values at my front-end textboxex
    2) whenever the user changes the front-end content it should change the corresponding value in the xml node.
    when it is finished i should be able to save the structure back as a xml file.This file is actually a blob object in the oracle database and is it wise to convert it into a file in dos directory and parse it from there or use oracle utilities from form6i and parse it from oracle utilities.
    Please if someone can find help on this ,it would really help me.

    No the password isn't your apple id password.
    You encrypted your backup with a password, if you don't remember the password, then i'm sorry you won't be able to use it.

  • Include xml from string

    If this xml would have been in file I could have used following code:
    <?xml version="1.0" encoding='WINDOWS-1252'?>
    <?xml-stylesheet type="text/xsl" href="t.xsl" ?>
    <page xmlns:xsql="urn:oracle-xsql">
    <xsql:include-xsql href="order_id_seq.xsql" reparse="no" />
    <xsql:include-xml href="order.xml"/>
    </page>
    But i will be getting xml as string .so could you please tell me how can i include a xml which i will be receiving as a string in xsql .
    Thanks

    I would like to correct the version informaiton. We are using SUN JAVA WEBSERVICES DEVELOPERS PACK (JWSDP1.1).
    Nathan

  • Parsing XML from a String

    I have a servlet, this recieves an XML file from the client as a file input type from a html form. This XML is wrapped up in http headers and stuff. I parse the input stream from the client's http request to get a string containing the xml. This is fine.
    How do I now build an XML document from this string? The DocumentBuilder will take in files and InputStreams but I can't find anything that helps me?
    The only solution I've come up with is to write out the string to a temp file and then parse it back into a Document.
    Any ideas anyone?????

    Document doc = documentBuilder.parse(new InputSource(new StringReader(yourXMLString)));
    voila!

  • Parse XML from a string

    Hi,
    I have a varchar2 column in one of my table and some rows in the table can save XML in the column. Now I have requirement to parse the xml save xml in the table and retrieve some critical information.
    How can I do this in PL/SQL? I have Oracle 10g database.
    Any help is appreciated.
    Thanks
    - Jaideep

    Hi,
    Check this link [XML Functions|http://www.psoug.org/reference/xml_functions.html]
    Regards,

Maybe you are looking for

  • GR/IR - Vendor information

    Hi, When create PO and IV in SAP, it would generate the postings as below, DR inventory/expense   CR  GR/IR DR GR/IR   CR Vendor We have added the offsetting information in vendor line item, but it would only show the GR/IR account, user wants to sho

  • Transfer Prior Year Asset to Multiple new assets

    Hello friends, We are required to breakdown one of our large Expansion Machinery Assets to multiple assets to reflect the main equipment purchased for the project. There is a transaction in SAP (ABUMN) Transfer with-in Company Code.  I think this tra

  • Backup iTunes library to external HD

    How can I select or point to an external hard drive to backup my iTunes library rather than use hundreds of CD's?

  • Urgent: Where to write HFM API objects coding in consolidation?

    Hi, I want to write a code on HsvProcessFlow library object to make some customized changes. But wondering where should i write this code. Is rules editor is the place where i should write the code. Please help me on this. Regards, Arvind

  • Transfering Info For Adobe Bridge To Aperture

    i am getting pictures worked with photoshop and tagged with metadata via adobe bridge and i was wondering if i could get the metadata information imported into aperture when i am importing the pictures. thanks for your help.