Parseing an XML Document as a String

Hi all,
i am trying to parse an XML document to a parser. I get the file as a request parameter, which is filled in to at String variable.
But for some reason i get an SAXException, does anyone se the problem?
Thank you for your help...
Below is the code
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.text.*;
import java.net.*;
import java.net.URL;
import java.sql.*;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import javax.xml.parsers.*;
import javax.xml.transform.stream.StreamSource;
public class StartServlet extends HttpServlet
private boolean debug = true;
private final static String CONTENT = "content";
private final static String COOKIES = "cookies";
String resp = new String();
private static String NODE_TYPES[] = new String[] {
     "ELEMENT",
     "ATTRIBUTE",
     "TEXT",
     "CDATA_SECTION",
     "ENTITY_REFERENCE",
     "ENTITY",
     "PROCESSING_INSTRUCTION",
     "COMMENT",
     "DOCUMENT",
     "DOCUMENT_TYPE",
     "DOCUMENT_FRAGMENT",
     "NOTATION" };
public static void println(String s, int indent) {
     for(int i = 0 ; i < indent; i++) {
               System.out.println(" ");
     System.out.println(s);
public static void println(String s) {
     System.out.println(s);
public static void print(Node node){
     printImpl(node, 0);
public static void printImpl(Node node, int indent){
     if(node == null) {
          return;
     String nodeType = NODE_TYPES[node.getNodeType()];
     String nodeName = node.getNodeName();
     String nodeValue = node.getNodeValue();
     if(nodeValue != null) {
          nodeValue = nodeValue.trim();
     if(nodeType.equals("TEXT") && nodeValue.equals("")) {
          ; //Ignore emty node
     else {
          println(nodeType + " - " + nodeName + " - " + nodeValue, indent);
     NamedNodeMap attributes = node.getAttributes();
     if (attributes != null) {
          for(int i = 0; i < attributes.getLength(); i++) {
               printImpl(attributes.item(i), indent + 1);
     NodeList children = node.getChildNodes();
     if(children != null) {
          for(int i = 0; i < children.getLength(); i++){
               printImpl(children.item(i), indent + 1);
public static DocumentBuilder newBuilder(boolean validation)
                    throws ParserConfigurationException {
     DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
     domFactory.setValidating(validation);
     domFactory.setNamespaceAware(true);
     DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
     //domBuilder.setErrorHandler(new PrintErrorHandler());
     return domBuilder;
public static Document newDocument()
                    throws ParserConfigurationException{
     DocumentBuilder domBuilder = newBuilder(false);
     Document document = domBuilder.newDocument();
     return document;
public static Document parse( String xml, boolean validation)
                    throws ParserConfigurationException, IOException, SAXException {
          DocumentBuilder domBuilder = newBuilder(validation);
          Document document = domBuilder.parse(xml);
          return document;
public void init() {
public void service( javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res) {
          String[] cookies = null;
          try{
               Hashtable document = getDocument("http://.../first.xml", cookies);
               resp = (String) document.get(CONTENT);
               debug(resp);
               print(parse(resp, false));
          catch (SAXParseException e){
               System.out.println("Saxfejl");
               //System.exit(1);
          catch (Exception e){
               e.printStackTrace();
               System.exit(1);
public void debug(String msg) {
     if(debug) {
          System.out.println(msg);
public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {
     try
          // Insert user code from here.
     catch(Throwable theException)
          // uncomment the following line when unexpected exceptions
          // are occuring to aid in debugging the problem.
          //theException.printStackTrace();
public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
     performTask(request, response);
public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
     performTask(request, response);
private Hashtable getDocument(String urlCode, String[] oldCookies) {
     Hashtable document = new Hashtable();
     HttpURLConnection http = null;
     try {
          URL httpURL = new URL(urlCode);
          // If HTTP Protocol, then open connection using the Request method indicated
          URLConnection conn = httpURL.openConnection();
          http = (HttpURLConnection) conn;
          //http.setRequestMethod("GET");
          http.setDoInput(true);
          http.setDoOutput(true);
          http.setUseCaches(false);
          http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
          if (oldCookies != null) {
               for (int j = 0; j < oldCookies.length; j++) {
                    String cookie = oldCookies[j];
                    http.setRequestProperty("Cookie", cookie);
          http.connect();
          http.getContent();
          StringBuffer tsb = new StringBuffer("");
          if (http.getResponseCode() == 200) {
               InputStream cis = http.getInputStream();
               byte[] a = new byte[1024];
               int n = cis.read(a);
               while (n >= 0) {
                    tsb.append(new String(a, 0, n));
                    n = cis.read(a);
               cis.close();
               document.put(CONTENT, tsb.toString());
          String[] cookies = null;
          if (cookies == null) {
               int headerFieldIndex = 0;
               String headerFieldValue = http.getHeaderField(headerFieldIndex);
               Vector cookieValues = new Vector();
               while (headerFieldValue != null) {
                    String headerFieldName = http.getHeaderFieldKey(headerFieldIndex);
                    if ((headerFieldName != null) && headerFieldName.toLowerCase().equals("set-cookie")) {
                         int index = headerFieldValue.indexOf(";");
                         if (index > -1) {
                              headerFieldValue = headerFieldValue.substring(0, index);
                         cookieValues.addElement(headerFieldValue);
                    headerFieldValue = http.getHeaderField(++headerFieldIndex);
               cookies = new String[cookieValues.size()];
               cookieValues.copyInto(cookies);
          document.put(COOKIES, cookies);
     catch (Exception e) {
          debug("url problem" + e);
     finally {
          if (http != null) {
               http.disconnect();
     return document;
}

Hi,
Use this code it will helpful to you.
resultXMLDocument=(XmlDocument)documentDoc;
StringWriter sw = new StringWriter();
resultXMLDocument.write((Writer) sw);
xmlString=sw.toString();
thnaks,
suneel

Similar Messages

  • How to create an XML document from a String.

    Can anyone help,
         In the Microsoft XML Document DOM there is a load function load(string) which will create an XML document, but now we are switching to Java and I do not know how to create and XML document from a string, this string �xml document� is passed to my program from a webservice and I need to read several xml elements form it in a web server.
    This string is a well formatted XML document:
    <?xml version="1.0" encoding="UTF-8"?>
    <Countries NumberOfRecords="1" LanguageID="en-us">
         <Country>
              <CountryCode>AU</CountryCode>
              <CountryName>AUSTRALIA</CountryName>
         </Country>
    </Countries>

    Thanks PC!
    I made it work using:
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    factory.setIgnoringComments(true); // We want to ignore comments
    // Now use the factory to create a DOM parser
    DocumentBuilder parser = factory.newDocumentBuilder();
    //TransformThisStringBuffer is a string buffer wich contain the 'XML document (String)'
    InputStream in = new ByteArrayInputStream(TransformThisStringBuffer.toString().getBytes());
    // Parse the InputStream and build the document
    Document document = parser.parse(in);
    But which one is faster InputSource or InputStream, were would you put the "new InputSource(new StringReader(yourString))" in the above code?

  • How do I parse a XML document?

    Hello
    I have a problem parsing a XML-document like the one below: Can anyone help me with a code example or something to get the tag "<Name>" out so that I get the string "Example5" and "Example3" out.
    Thnx for any help!
    Jimmy
    The XML file looks like this (but without the line in the beginning of each row):
    <?xml version="1.0" encoding="UTF-8"?>
    <!-- edited with XML Spy v4.4 U (http://www.xmlspy.com) -->
    <!DOCTYPE ThisExample SYSTEM "C:/example.dtd">
    <?xml-stylesheet type="text/xsl" href="first.xslt"?>
    <ThisExample>
    ____<Product>
    ________<Product_number>no1</Product_number>
    ________<Number>number1</Number>
    ____</Product>
    ____<Product>
    ________<Product_number>no2</Product_number>
    ________<Number>number2</Number>
    ____</Product>
    ____<Group>
    ________<Type>EX1</Type>
    ________<ProductVersionAllowed>Y</ProductVersionAllowed>
    ________<Preprocess>precmd.csh</Preprocess>
    ________<Postprocess>echo Finished</Postprocess>
    ________<Document>
    ____________<Name>Example1</Name>
    ____________<Product_number>no1</Product_number>
    ____________<Ticked_by_default>Y</Ticked_by_default>
    ________</Document>
    ________<Document>
    ____________<Name>Example2</Name>
    ____________<Product_number>no1</Product_number>
    ____________<Ticked_by_default>Y</Ticked_by_default>
    ________</Document>
    ________<Document>
    ____________<Name>Example3</Name>
    ____________<Product_number>no1</Product_number>
    ____________<Ticked_by_default>Y</Ticked_by_default>
    ________</Document>
    ____</Group>
    ____<Group>
    ________<Type>EX2</Type>
    ________<ProductVersionAllowed>N</ProductVersionAllowed>
    ________<Preprocess>precmd.csh</Preprocess>
    ________<Postprocess>echo Finished</Postprocess>
    ________<Document>
    ____________<Name>Example4</Name>
    ____________<Product_number>no2</Product_number>
    ____________<Ticked_by_default>Y</Ticked_by_default>
    ________</Document>
    ________<Document>
    ____________<Name>Example5</Name>
    ____________<Product_number>no2</Product_number>
    ____________<Ticked_by_default>Y</Ticked_by_default>
    ________</Document>
    ____</Group>
    </ThisExample>

    Thnx :O)
    Now it worx!
    Just one more thing. Can I get the number of elements there is in a tag? I.e. how many "Document"'s there are in 1 "Group"? I need this because I have too loop through a "Group" and print the name of every "Document".
    At the moment I'm doing it like below, but that is not a nice solution, and it realy does not work that well:
    Jimmy
    int i = 1;
    do
    node = org.apache.xpath.XPathAPI.selectSingleNode(doc, "/PosttoolControl/Group[position()=" + i + "]/Type");
    if (node.getFirstChild().getNodeValue() != null)
    type = node.getFirstChild().getNodeValue();
    PostToolDocGroupeComboBox.addItem(type);
    i++;
    } while (node.getFirstChild().getNodeValue() != null);

  • Unable to display tree view; Error when parsing an XML document (Premature end of file.)

    Hi folks,
    I am using a cascaded mapping in my OM. I have a graphical mapping followed by the Java mapping. It is a flat file to IDOC mapping. Everything works fine in Dev but when I transport the same objects to QA, the Operation mapping though it doesn't fail in ESR testing tool, gives the following message and there is no output generated for the same payload which is successfully tested in DEV. Please advise on what could be the possible reasons.
    Unable to display tree view; Error when parsing an XML document (Premature end of file.)

    kalyan,
    There seems to be an invalid xml payload which causes this error in ESR not generating the tree view. Please find the similar error screenshot and rectify the payload.
    Mutti

  • Parsing an xml document inside a Thread

    Hi Friends
    I have to do some processing in my application for which i need to use multithreading.
    Inside every new thread created i have to parse an xml document using s parsing tool like castor or jibx.
    My question is that is it possible to parse a xml document inside a new thread everytime it gets created.
    is it a good coding practice as it involves java code to do it.
    Thanks
    Vikeng

    vikeng wrote:
    Hi
    Thanks for the reply.
    Well i need to do some kind of a batch processing in my application.
    I need to parse an xml document and upload the data i get after parsing into columns in the database.
    Since its a batch what i was asking was is it possible to do it for every request as batch needs to handle hundreds of records during the daily or nightly sync.
    Is it a good practice to do parsing for every record in a batch
    Thanks
    VikengI don't get it. One batch is one document, and that document contains e.g. 100 records? What's one request? A request for one batch? I would execute one batch in one thread.
    Kaj

  • How to parse multiple xml documents from single buffer

    Hello,
    I am trying to use jaxb 2.0 to parse a buffer which contains multiple xml documents. However, it seems that it is meant to only parse a single document at a time and throws an exception when it gets to the 2nd document.
    Is there a way I can tell jaxb to only parse the first complete document and not fetch the next one out of the buffer? Or what is the most efficient way to separate the buffer into two documents without parsing it manually. If I have to search the buffer for the next document root and then split the buffer, it seems like that defeats the purpose of using jaxb as the parser.
    I am using the Unmarshaller.unmarshall method and the exception I am getting is:
    org.xml.sax.SAXParseException: Illegal character at end of document, &#x3c;.]
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:315)
         at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:476)
         at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:198)
         at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:167)
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137)
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:184)
    Thank you for your help

    It's just like any other XML parser, it's only designed to parse one XML document. If you have something that concatenates two XML documents together (that's what your "buffer" sounds like), then stop doing that.

  • Error when parsing the XML document

    hi all.
    i have the next problem.
    the sender sistem send to XI an XML. some tags send a '#' caracter.
    Sender Service send:
    Torre B1 - B#Unimev
    when Im traying to test XML inbound, XI show the next error:
    Error when parsing the XML document (Fatal Error: com.sap.engine.lib.xml.parser.ParserException: Invalid char #0x14(:main:, row:1, col:992))
    XML:
      <?xml version="1.0" encoding="UTF-8" ?>
    - <ZDEBMAS6>
    -   <IDOC BEGIN="1">
    -      <EDI_DC40 SEGMENT="1">
             <TABNAM>EDI_DC40</TABNAM>
             <MANDT>300</MANDT>
             <DOCNUM>0000000000339708</DOCNUM>
             <DOCREL>640</DOCREL>
             <STATUS>30</STATUS>
             <DIRECT>1</DIRECT>
             <OUTMOD>2</OUTMOD>
           </EDI_DC40>
    -      <E1KNA1M SEGMENT="1">
              <MSGFN>009</MSGFN>
              <REGIO>07</REGIO>
              <STCD1>20147972750</STCD1>
              <FITYP>01</FITYP>
              <STCDT>80</STCDT>
              <STCD3>0</STCD3>
    -         <Z1KNA1M SEGMENT="1">
                 <MSGFN>009</MSGFN>
                  <KUNNR>0001000563</KUNNR>
                  <ZZSOCRCV>3100</ZZSOCRCV>
                  <ZZGBDAT>00000000</ZZGBDAT>
              <b> <ZZAD_STREET_CO>Torre B1 - B Unimev</ZZAD_STREET_CO></b>
                  <ZZAD_ROOMNUM_CO>PB</ZZAD_ROOMNUM_CO>
                  <ZZAD_FLOOR_CO>E</ZZAD_FLOOR_CO>
                  <ZZAD_PSTCD1_CO>M5521AAR</ZZAD_PSTCD1_CO>
                  <ZZAD_CITY1_CO>Mendoza</ZZAD_CITY1_CO>
                  <ZZAD_REGIO_CO>07</ZZAD_REGIO_CO>
               </Z1KNA1M>
               <Z1ADRCM SEGMENT="1">
                  <MSGFN>009</MSGFN>
                  <KUNNR>0001000563</KUNNR>
               <b><STREET>Torre B1 - B Unimev</STREET></b>
                  <FLOOR>PB</FLOOR>
                  <HOUSE_NUM2>E</HOUSE_NUM2>
                  <CITY1>Mendoza</CITY1>
                  <POST_CODE1>5521</POST_CODE1>
                  <COUNTRY>AR</COUNTRY>
                  <REGION>07</REGION>
                  <LANGU>S</LANGU>
              </Z1ADRCM>
          </E1KNA1M>
        </IDOC>
    </ZDEBMAS6>
    Message was edited by: Rodrigo Pertierra
    Message was edited by: Rodrigo Pertierra

    Hi Rodrigo,
    Do you use a specific "encoding" like UTF-8 or ISO-8859-1 in your Sender CC.
    Try changing the Transfer mode to Binary instead of Text.
    Also go through these links:-
    http://help.sap.com/saphelp_nw2004s/helpdata/en/e3/94007075cae04f930cc4c034e411e1/content.htm
    Invalid char in XML from inbound IDoc
    Hope this provides a solution.
    Regards.
    Praveen

  • Issue with parsing an xml document and namespaces

    I am having an issue when parsing an xml document that includes a namespace.
    Here is my xml:
    <?xml version="1.0" encoding="utf-8"?>
    <StatusFile xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" TxCnt="247" TxTotal="5756845.31" SourceId="3" xmlns="http://www.test.com/cig/payments/optimizer/status/2004/10/">
    <Tx PmtId="350031" Amt="16739" TxSts="09" CustSts="04" ChkNum="10605770" />
    <Tx PmtId="350990" Amt="31698.66" TxSts="09" CustSts="04" ChkNum="10605821" />
    <Tx PmtId="354992" Amt="201320.08" TxSts="09" CustSts="04" />
    <Tx PmtId="349277" Amt="6675.17" TxSts="09" CustSts="04" ChkNum="10605822" />
    <Tx PmtId="354979" Amt="66949.75" TxSts="09" CustSts="04" ChkNum="10605823" />
    <Tx PmtId="349341" Amt="63258.49" TxSts="09" CustSts="04" ChkNum="10605824" />
    <Tx PmtId="350025" Amt="5866.04" TxSts="09" CustSts="04" ChkNum="10605830" />
    <Tx PmtId="350024" Amt="15671.8" TxSts="09" CustSts="04" ChkNum="10605831" />
    <Tx PmtId="346822" Amt="9880.64" TxSts="09" CustSts="04" />
    <Tx PmtId="350023" Amt="1360" TxSts="09" CustSts="04" />
    <Tx PmtId="349802" Amt="131267" TxSts="09" CustSts="04" ChkNum="10605832" />
    <Tx PmtId="343573" Amt="14532.76" TxSts="09" CustSts="04" ChkNum="10605833" />
    <Tx PmtId="352675" Amt="4436" TxSts="09" CustSts="04" />
    <Tx PmtId="350022" Amt="1260" TxSts="09" CustSts="04" ChkNum="10605834" />
    <Tx PmtId="349714" Amt="80778" TxSts="09" CustSts="04" ChkNum="10605835" />
    <Tx PmtId="352676" Amt="10136" TxSts="09" CustSts="04" ChkNum="10605836" />
    <Tx PmtId="352679" Amt="25511.69" TxSts="09" CustSts="04" ChkNum="10605837" />
    <Tx PmtId="346502" Amt="12842.69" TxSts="10" CustSts="05" />
    <Tx PmtId="346503" Amt="4232.61" TxSts="09" CustSts="04" ChkNum="10605838" />
    </StatusFile>
    Here is my current code base:
    CREATE OR REPLACE PROCEDURE ParseXML(xml VARCHAR2) IS
    myParser xmlparser.parser := xmlparser.newparser;
    myDoc xmldom.DOMNode;
    myNodes xmldom.DOMNodeList;
    myElement xmldom.DOMElement;
    trec NDE_CIG_STATUS_TRANSACTIONS%ROWTYPE;
    BEGIN
    xmlparser.parseBuffer(myParser,xml);
    myDoc := xmldom.makeNode(xmlparser.getDocument(myParser));
    myNodes := xslprocessor.selectNodes(myDoc,'//Tx');
    FOR i IN 0..xmldom.getLength(myNodes)-1 LOOP
    myElement := xmldom.makeElement(xmldom.item(buyOrders,i));
    trec.pmt_id := xmldom.getAttribute(curBuy,'PmtId');
    INSERT INTO NDE_CIG_STATUS_TRANSACTIONS(PMT_ID) VALUES (trec.pmt_id);
    END LOOP;
    COMMIT;
    END ParseXML;
    If I remove the namespace, everything works just fine. The issue is that I cannot remove the namespace.
    Anyone have any suggestions on how I can get the xslprocessor.selectNodes to recognize my namespace?
    Thanks,
    Mark Moran

    Everyone,
    Well after lots of hours spent reading web pages and blogs, etc... I was able to re-write my procedure and get it to work with different calls.
    Here is my updated code.
    PROCEDURE PARSE_STATUS_XML(P_FILE_NAME IN VARCHAR2, P_XML_FILE IN CLOB) IS
    V_PARSER XMLPARSER.PARSER := XMLPARSER.NEWPARSER;
    V_DOCUMENT XMLDOM.DOMDOCUMENT;
    V_NODES XMLDOM.DOMNODELIST;
    V_ELEMENT XMLDOM.DOMELEMENT;
    V_TBL_RECORD NDE_CIG_STATUS_TRANSACTIONS%ROWTYPE;
    BEGIN
    XMLPARSER.PARSECLOB(V_PARSER, P_XML_FILE);
    V_DOCUMENT := XMLPARSER.GETDOCUMENT(V_PARSER);
    V_ELEMENT := XMLDOM.GETDOCUMENTELEMENT(V_DOCUMENT);
    V_NODES := XMLDOM.GETELEMENTSBYTAGNAME(V_ELEMENT,'Tx','http://www.test.com/cig/payments/optimizer/status/2004/10/');
    FOR I IN 0..XMLDOM.GETLENGTH(V_NODES)-1 LOOP
    V_ELEMENT := XMLDOM.MAKEELEMENT(XMLDOM.ITEM(V_NODES,I));
    V_TBL_RECORD.PMT_ID := XMLDOM.GETATTRIBUTE(V_ELEMENT,'PmtId');
    V_TBL_RECORD.PMT_AMT := XMLDOM.GETATTRIBUTE(V_ELEMENT,'Amt');
    V_TBL_RECORD.E_STATUS_CODE := XMLDOM.GETATTRIBUTE(V_ELEMENT,'TxSts');
    V_TBL_RECORD.E_REASON_CODE := XMLDOM.GETATTRIBUTE(V_ELEMENT,'StsRsn');
    V_TBL_RECORD.E_CUSTOMER_STATUS_CODE := XMLDOM.GETATTRIBUTE(V_ELEMENT,'CustSts');
    V_TBL_RECORD.UPS_TRACKING_NBR := XMLDOM.GETATTRIBUTE(V_ELEMENT,'UpsTrcNum');
    V_TBL_RECORD.FED_REFERENCE_NBR := XMLDOM.GETATTRIBUTE(V_ELEMENT,'FedRefNum');
    V_TBL_RECORD.FIDB_TRACKING_NBR := XMLDOM.GETATTRIBUTE(V_ELEMENT,'FIDbtTrcNum');
    V_TBL_RECORD.CHECK_NBR := XMLDOM.GETATTRIBUTE(V_ELEMENT,'ChkNum');
    INSERT INTO NDE_CIG_STATUS_TRANSACTIONS(
    CREATE_DATE,
    XML_FILE_NAME,     
    PMT_ID,
    PMT_AMT,
    E_STATUS_CODE,
    E_REASON_CODE,
    E_CUSTOMER_STATUS_CODE,
    UPS_TRACKING_NBR,
    FED_REFERENCE_NBR,
    FIDB_TRACKING_NBR,
    CHECK_NBR
         VALUES (
    SYSDATE,
    P_FILE_NAME,
    V_TBL_RECORD.PMT_ID,
    V_TBL_RECORD.PMT_AMT,
    V_TBL_RECORD.E_STATUS_CODE,
    V_TBL_RECORD.E_REASON_CODE,
    V_TBL_RECORD.E_CUSTOMER_STATUS_CODE,
    V_TBL_RECORD.UPS_TRACKING_NBR,
    V_TBL_RECORD.FED_REFERENCE_NBR,
    V_TBL_RECORD.FIDB_TRACKING_NBR,
    V_TBL_RECORD.CHECK_NBR
    END LOOP;
    COMMIT;
    EXCEPTION
    WHEN OTHERS THEN
         RAISE;
    END PARSE_STATUS_XML;
    Mark

  • My Task is To Parse a XML Document to Return CLOB's

    Hi folks
    I am writing this mail in the hope of getting a help.Please
    give me a shoulder to keep me going.
    The task is to parse a XML document for a specific Tag and
    read the Tag content in CLOB to return CLOB.
    I know that the writetoclob will do the job as
    per oracle documentation.
    I am giving the code where i got stuck.
    Please help me complete my rest of coding.
    Thanks
    Input variables are
    XMLin in CLOB, -- Incoming XML Document Structure
    Partype in varchar2, -- Tagname
    Result out CLOB -- Return Tag value CLOB data type.
    My Code : -
    Declare
    p xmlparser.parser;
    d xmldom.DOMDocument;
    e xmldom.DOMElement;
    nl xmldom.DOMNodeList;
    n xmldom.DOMNode;
    tagvalue varchar2(255);
    paramsIn Clob;
    result CLOB;
    BEGIN
    --loading SecXML
    dbms_lob.createtemporary(paramsIn,true);
    dbms_lob.append(paramsIn,XMLin);
    --dbms_output.put_line('ParsebyTag ='||Partype);     
    --defining parser
    p := xmlparser.newparser;
    xmlparser.parseClob(p,paramsIn);
    d := xmlparser.getDocument(p);
    --get tagvalue
    nl := xmldom.getElementsByTagName(d,partype);
    n := xmldom.item(nl,0);
    IF xmldom.getlength (nl) > 0
    THEN
    n := xmldom.item (nl, 0);
    =>=>=> => xmldom.writetoclob (n, result); <=<=<=<=<=<=====
    END IF;
    return; -- from a procedure
    The above line marked with a arrow does not work for CLOB Variables.
    Please explain with a corrected code to complete this task.
    Thanks for reading my request.
    Please reply to this message poster as i am frequently
    checking this to see a answer.
    my email is [email protected]
    Balaji.

    First, you have 2 variables with the same name,
    Second, let me show you what is that you need to do:
    PROCEDURE WriteDataToClob(XMLin in CLOB, Partype in varchar2, Result out CLOB) IS
    Declare
    p xmlparser.parser;
    d xmldom.DOMDocument;
    e xmldom.DOMElement;
    nl xmldom.DOMNodeList;
    n xmldom.DOMNode;
    tagvalue varchar2(255);
    TempClob Clob;
    BEGIN
    --Create a temporary clob
    dbms_lob.createtemporary(TempClob,true);
    --loading SecXML
    --defining parser
    p := xmlparser.newparser;
    xmlparser.parseClob(p,XMLin);
    d := xmlparser.getDocument(p);
    --get tagvalue
    nl := xmldom.getElementsByTagName(d,partype);
    n := xmldom.item(nl,0);
    IF xmldom.getlength (nl) > 0 THEN
    n := xmldom.item (nl, 0);
    xmldom.writetoclob (n, TempClob );
    END IF;
    Result := TempClob;
    dbms_lob.FreeTemporary(TempClob);
    END;

  • Poweshell script to parse a XML document to get all Leaf level nodes with Node names in CSV

    Hi Experts,
    I want to write a Powershell script to parse a XML document to get all Leaf level nodes with Node names in CSV
    <?xml version="1.0" encoding="UTF-8"?>
    <CATALOG>
       <CD>
          <TITLE>Empire Burlesque</TITLE>
          <ARTIST>Bob Dylan</ARTIST>
          <COUNTRY>USA</COUNTRY>
          <COMPANY>Columbia</COMPANY>
          <PRICE>10.90</PRICE>
          <YEAR>1985</YEAR>
       </CD>
    </CATALOG>
    Need to display this as
    CD_Tiltle, CD_ARTIST, CD_COUNTRY, CD_COMPANY, CD_PRICE, CD_YEAR
    Empire Burlesque, Bob Dylan,USA,Columbia,10.90,1985
    and so on..
    I do not want to hard code the tag names in the script.
    current example is 2 level hierarchy XML can be many level till 10 max I assume
    in that case the csv file field name will be like P1_P2_P3_NodeName as so on..
    Thanks in advance
    Prajesh

    Thankfully, I have writtenscript for ths same $node_name="";
    $node_value="";
    $reader = [system.Xml.XmlReader]::Create($xmlfile)
    while ($reader.Read())
    while ($reader.Read())
    if ($reader.IsStartElement())
    $node_name += "," + $reader.Name.ToString();
    if ($reader.Read())
    $node_value += "," + $reader.Value.Trim();
    Thanks and Regards, Prajesh Please use Marked as Answer if my post solved your problem and use Vote As Helpful if a post was useful.

  • How to parse an XML document with oracle8i

    Has anyone a good link or an example how to decode and store an XML document into an oracle8i database.
    I' ve found only good things for oracle9i.
    Thank you
    Roger

    Here is an example of parsing xml taken fro Oracle8i 8.1.7 xdk.
    This one uses external OS files to pase, but could be easily converted to
    use CLOB or VARCHAR2 string for parsing XML documents.
    IF you wanted to use CLOB to store and manipulate xml documents you can use XMLParser and XMLDom
    packages along with the DBMS_LOB package to do that.
    -- This file demonstates a simple use of the parser and DOM API.
    -- The XML file that is given to the application is parsed and the
    -- elements and attributes in the document are printed.
    -- The use of setting the parser options is demonstrated.
    set serveroutput on;
    create or replace procedure domsample(dir varchar2, inpfile varchar2,
    errfile varchar2) is
    p xmlparser.parser;
    doc xmldom.DOMDocument;
    -- prints elements in a document
    procedure printElements(doc xmldom.DOMDocument) is
    nl xmldom.DOMNodeList;
    len number;
    n xmldom.DOMNode;
    begin
    -- get all elements
    nl := xmldom.getElementsByTagName(doc, '*');
    len := xmldom.getLength(nl);
    -- loop through elements
    for i in 0..len-1 loop
    n := xmldom.item(nl, i);
    dbms_output.put(xmldom.getNodeName(n) || ' ');
    end loop;
    dbms_output.put_line('');
    end printElements;
    -- prints the attributes of each element in a document
    procedure printElementAttributes(doc xmldom.DOMDocument) is
    nl xmldom.DOMNodeList;
    len1 number;
    len2 number;
    n xmldom.DOMNode;
    e xmldom.DOMElement;
    nnm xmldom.DOMNamedNodeMap;
    attrname varchar2(100);
    attrval varchar2(100);
    begin
    -- get all elements
    nl := xmldom.getElementsByTagName(doc, '*');
    len1 := xmldom.getLength(nl);
    -- loop through elements
    for j in 0..len1-1 loop
    n := xmldom.item(nl, j);
    e := xmldom.makeElement(n);
    dbms_output.put_line(xmldom.getTagName(e) || ':');
    -- get all attributes of element
    nnm := xmldom.getAttributes(n);
    if (xmldom.isNull(nnm) = FALSE) then
    len2 := xmldom.getLength(nnm);
    -- loop through attributes
    for i in 0..len2-1 loop
    n := xmldom.item(nnm, i);
    attrname := xmldom.getNodeName(n);
    attrval := xmldom.getNodeValue(n);
    dbms_output.put(' ' || attrname || ' = ' || attrval);
    end loop;
    dbms_output.put_line('');
    end if;
    end loop;
    end printElementAttributes;
    begin
    -- new parser
    p := xmlparser.newParser;
    -- set some characteristics
    xmlparser.setValidationMode(p, FALSE);
    xmlparser.setErrorLog(p, dir || '/' || errfile);
    xmlparser.setBaseDir(p, dir);
    -- parse input file
    xmlparser.parse(p, dir || '/' || inpfile);
    -- get document
    doc := xmlparser.getDocument(p);
    -- Print document elements
    dbms_output.put('The elements are: ');
    printElements(doc);
    -- Print document element attributes
    dbms_output.put_line('The attributes of each element are: ');
    printElementAttributes(doc);
    -- deal with exceptions
    exception
    when xmldom.INDEX_SIZE_ERR then
    raise_application_error(-20120, 'Index Size error');
    when xmldom.DOMSTRING_SIZE_ERR then
    raise_application_error(-20120, 'String Size error');
    when xmldom.HIERARCHY_REQUEST_ERR then
    raise_application_error(-20120, 'Hierarchy request error');
    when xmldom.WRONG_DOCUMENT_ERR then
    raise_application_error(-20120, 'Wrong doc error');
    when xmldom.INVALID_CHARACTER_ERR then
    raise_application_error(-20120, 'Invalid Char error');
    when xmldom.NO_DATA_ALLOWED_ERR then
    raise_application_error(-20120, 'Nod data allowed error');
    when xmldom.NO_MODIFICATION_ALLOWED_ERR then
    raise_application_error(-20120, 'No mod allowed error');
    when xmldom.NOT_FOUND_ERR then
    raise_application_error(-20120, 'Not found error');
    when xmldom.NOT_SUPPORTED_ERR then
    raise_application_error(-20120, 'Not supported error');
    when xmldom.INUSE_ATTRIBUTE_ERR then
    raise_application_error(-20120, 'In use attr error');
    end domsample;
    show errors;

  • Storing and parsing  an XML document

    Hi everybody,
    does anybody know how to store (clob) and to parse (query) and XML document? can you give me an example and/or some useful information?
    Thanx in advance,
    Ettore

    Hi, first try determine how much time does the parsing xml get,
    you could just remove insert lines, and count,
    if the time is similar it means that parsing xml has great infulance on total time,
    otherwise there is insert affection you could try ue forall loop syntax insted of for ( just FORALL currentNode IN 0 .. xmldom.getLength(nodeList) - 1 LOOP) or
    direct load using 'insert into <table_name> .. as select',
    'forall' minimize conext switches it could help
    to achive direct load you need first rewrite your procedure to function in order to return table, (table of object ), so your insert could look like
    insert into SWTable
    as select * from table
    (cast
    USP_FILEINFOINSTANCEINSERT(
    URLFile =>x
    lComputerID =>y) as SWTable_t)
    where SWTable_t - table of SWTable_o
    SWTable_o - object with all SWTable's atributes

  • XML document convert into String and Insert into Database

    Hello all,
         In the FIle to File Scenario  I want to send the data to the Reciever System in xml Document and convert into String and insert into Database.
      Please can you tell me exact way how to send it.
    Thanks & Regards,
    Raj

    HI,
    As per my understanding your scenario is File to file where you will get output fiel in XML format.
    Now that XMl payload need to be passed as single string in the database via XI.
    You cauld do this but you need to imply some manipulations such as
    With the help of standard API you need to concatenate the  XML tags and create the structre along with the data.
    For e.g. in your outpuf file the XML structre contain data as
    <field1>ABCD</field1>
    Then in mapping
    The source field will be mappeda s concat(<field1>) + value of  Source field "ABCD" + concat(</field1>) to the target field.
    This is the way that you could achive the requirments else there is no direct way avaialble for it.
    thanks
    Swarup

  • How to get the WHOLE xml document inside a string using XSLT mapping

    Hi folks,
    I have a deep xml structure that I want to embed as body, tags included, in a mail message (not as an attachment).
    I'm trying to use Michal's method in this blog
    /people/michal.krawczyk2/blog/2005/11/01/xi-xml-node-into-a-string-with-graphical-mapping
    However, I can't get it to deliver the entire structure instead of just specific elements.
    Any help is greatly appreciated,
    Thanks,
    Guy

    Ashok,
    I was able to work it out for my case.
    This XSL......
    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
    <inside>
    <namestring>
    <xsl:text disable-output-escaping="yes"><![CDATA[<![CDATA[]]></xsl:text>
    <xsl:copy-of select="outside/name/*"/>
    <xsl:text disable-output-escaping="yes"><![CDATA[]]]]></xsl:text>
    <xsl:text disable-output-escaping="yes"><![CDATA[>]]></xsl:text>
    </namestring>
    </inside>
    </xsl:template>
    </xsl:stylesheet>
    ...will transform this input....
    <?xml version="1.0" encoding="UTF-8"?>
    <outside>
    <name>
    <nameone>name1</nameone>
    <nametwo>name2</nametwo>
    <namethree>name3</namethree>
    </name>
    </outside>
    ...and put the whole lot into the CDATA element.
    Hope this helps you,
    Guy

  • Problem in parsing huge XML document

    Hi,
    i am getting the problem when trying to parse xml doc. which contains data more then 1 lacs. using jaxp (i.e. NodeList). i get the execption outofmemory.

    Which implementation of JAXP are you using? If it is a large file containing many of the same "documents", then consider using SAX as it is an event driven parser meaning it does not have to read the whole of the file before it can start processing it. Instead, it fires events when it sees the beginning and end of a "document" and also on completion of the elements. You can then create and destroy objects during the document processing stage which helps keep the memory consumption under control.

Maybe you are looking for

  • I tried to copy my itunes library to new drive now I'm in trouble

    I bought a new 1tb internal drive and installed it. I wanted a dedicated spot for a 500 gig music library and a place for dedicated backup. The man at micro center told me in order to move the library from the 1tb lacie external drive to the new driv

  • How to Install Win 7 ODBC for All Users?

    I installed the Windows 7 64-bit ODBC drivers, but the install does not seem to have made the drivers available to all users, but rather only the installing user. This install is for an image that will be cloned as a virtual machine, so the drivers,

  • Problem in creating entity service record

    Hello!!! I am creating new record in service     AEs_Employee emp;     emp = es_EmployeeServiceProxy.create();     emp.setPernr("12345123");     emp.getAspect().sendChanges(); Some mistakes occur during application launch: The initial exception that

  • Anti-Alias, Smart Objects and Photoshop

    I'm using photoshop to create a poster for a client of mine. I placed vector graphics from illustrator into my photoshop document, creating smart objects. As you can see, below, it looks like an Anti-Aliasing issue, where jagged lines are EVERYWHERE.

  • Powerbook G4 12" Version 10.5.8 Blue screen on startup.

    I have a problem with my Powerbook G4 12". Whenever I start it up I get the chime then I hear the buzzing of the computer and soon after I see the gray screen with the apple logo. But this is where the problem starts; after going through the grey scr