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.

Similar Messages

  • XML String to XML Parsing

    I have stored an XML file as a CLOB in the Oracle DB. While fetching this data into JCD in JavaCAPS 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.

    The forum itself is a good starting point : [http://forum.java.sun.com/thread.jspa?forumID=34&threadID=347151] is a result searching for "parse string"...

  • Conversion of xml string to xml file

    To convert xml string to xml file in java i used
    Document XMLDoc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader("<root><main>Title</main></root&g t;")));
    But it is showing an error as InputSource cannot be resolved
    How to rectify this

    I assume you mean there is a compiler error? (It helps if you explain your problem instead of just giving a vague description of it.) It sounds like you have to import InputSource. You do know about the import statements that go at the beginning of a Java class, don't you?

  • Convert XML string into XML

    Hi All,
    Can you please let me know for any sample code in xslt/java mapping for converting XML string into XML. We use SAP Pi 7.0
    My XML string starts like this
    <?xml version="1.0" encoding="UTF-8" ?> 
    - <ns0:MT_ReceiverFileStructure <namespace>"><Output><?xml version="1.0" encoding="ISO-8859-9"?><?xml-stylesheet type="text/xsl" href="<xsl>"?><Tarih_Date Tarih="11.09.2014" Date="09/11/2014>
       Thanks,
       Pavithra

    Thanks Praveen. It worked.
    However, the xml i have is an extract from a exchange rate URL and it has the reference to a xsl in it as below
    <?xml version="1.0" encoding="ISO-8859-9"?><?xml-stylesheet type="text/xsl" href="<ABC.xsl>"?>.
    So there is an error in sxmb_moni. Is it possible to remove this.

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

  • Insert XML String into XML file at a certain position

    Hello,
    I have this xml string:
    <jdbc-driver-params>
    <url>jdbc:oracle:thin:@localhost:1521:mydb</url>
    <driver-name>oracle.jdbc.OracleDriver</driver-name>
    <properties>
    <property>
    <name>user</name>
    <value>myuser</value>
    </property>
    </properties>
    <password-encrypted>myuser</password-encrypted>
    </jdbc-driver-params>and i need to insert it into an xml file at a certain position (as child for a node)
    The xml file looks like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <jdbc-data-source xmlns="http://www.bea.com/ns/weblogic/90"
        xmlns:sec="http://www.bea.com/ns/weblogic/90/security"
        xmlns:wls="http://www.bea.com/ns/weblogic/90/security/wls"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/920 http://www.bea.com/ns/weblogic/920.xsd">
        <name>myDB</name>
        <jdbc-data-source-params>
            <global-transactions-protocol>OnePhaseCommit</global-transactions-protocol>
        </jdbc-data-source-params>
    </jdbc-data-source>And this is how I would like to get it in the end:
    <?xml version='1.0' encoding='UTF-8'?>
    <jdbc-data-source xmlns="http://www.bea.com/ns/weblogic/90" xmlns:sec="http://www.bea.com/ns/weblogic/90/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wls="http://www.bea.com/ns/weblogic/90/security/wls" xsi:schemaLocation="http://www.bea.com/ns/weblogic/920 http://www.bea.com/ns/weblogic/920.xsd">
      <name>mydb</name>
      <jdbc-driver-params>
        <url>jdbc:oracle:thin:@localhost:1521:myDB</url>
        <driver-name>oracle.jdbc.OracleDriver</driver-name>
        <properties>
          <property>
            <name>user</name>
            <value>myuser</value>
          </property>
        </properties>
        <password-encrypted>myuser</password-encrypted>
      </jdbc-driver-params>
      <jdbc-connection-pool-params>
        <test-table-name>SQL SELECT 1 FROM DUAL</test-table-name>
      </jdbc-connection-pool-params>
      <jdbc-data-source-params>
        <global-transactions-protocol>OnePhaseCommit</global-transactions-protocol>
      </jdbc-data-source-params>
    </jdbc-data-source>So, I obtain the node for the given xml string, the jdbc-data-source node from the xml file and i attempt the appendChild. The problem is that nothing really gets inserted into the xml file.
    Someone, any idea?
    My code:
    try
                   DOMParser parser = new DOMParser();
                   parser.parse(xmlFileName);
                   Document doc = parser.getDocument(); // the document we will insert node into
                   Node root = doc.getElementsByTagName("jdbc-data-source").item(0);
                   //get XML string node
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder db = factory.newDocumentBuilder();
                   InputSource inStream = new InputSource();
                   inStream.setCharacterStream(new StringReader(xmlString));
                   Document doc4XMLString = db.parse(inStream);
                   Node rootXMLString = doc4XMLString.getElementsByTagName("jdbc-driver-params").item(0);
                   root.appendChild(doc.importNode(rootXMLString, true));
                   return true;
              catch (Exception e)
                   e.printStackTrace();
              }Thanks,
    johnny
    Edited by: smeag0l on Aug 6, 2008 5:08 PM
    Edited by: smeag0l on Aug 6, 2008 5:43 PM

    Well, you helped me again :-) Thank you very much!
    Here is how the code should look:
                            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder db4XMLFile = factory.newDocumentBuilder();
                   Document doc4XMLFile = db4XMLFile.parse(xmlFileName);
                   Node root4XMLFile = doc4XMLFile.getElementsByTagName(rootNodeName).item(0);
                   DocumentBuilder db4XMLString = factory.newDocumentBuilder();
                   InputSource inStream = new InputSource();
                   inStream.setCharacterStream(new StringReader(xmlString));
                   Document doc4XMLString = db4XMLString.parse(inStream);
                   Node root4XMLString = doc4XMLString.getElementsByTagName(xmlStringNodeName).item(0);
                   root4XMLFile.appendChild(doc4XMLFile.importNode(root4XMLString, true));
                   File file = new File(xmlFileName);
                            Result result = new StreamResult(file.toURI().getPath());
                   Source source = new DOMSource(doc4XMLFile);
                   Transformer xformer = TransformerFactory.newInstance().newTransformer();
                      xformer.transform(source, result);

  • REG: WRITE XML STRING INTO XML FILE

    Hi All, I have a XML FILE on PC. I get a xml string from my server.
    My Task: I want to append the xml string coming from the server into the existing xml file at a particular Node. Given below is my code :
    String xmlString = baos.toString();
                      DocumentBuilder db4XMLString = docBuilderFactory.newDocumentBuilder();
                      InputSource inStream = new InputSource();
                      inStream.setCharacterStream(new StringReader(xmlString));
                      Document doc4XMLString = db4XMLString.parse(inStream);
                      Node root4XMLString = doc4XMLString.getElementsByTagName("epg").item(0);
                      doc.appendChild(doc.importNode(root4XMLString, true));
                      File file = new File(Constant.XMLFILEPATH);
                      Result result = new StreamResult(file.toURI().getPath());
                      Source source = new DOMSource(doc);
                      Transformer xformer = TransformerFactory.newInstance().newTransformer();
                      xformer.transform(source, result);But, wen i run my application I get following exception:
    The markup in the document following the root element must be well-formed.
    org.xml.sax.SAXParseException: The markup in the document following the root element must be well-formed.
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    Is that my XML string is not well formed. Is it so then please let me how to convert my xml string into well formed XML data.
    Please help me out.
    Thanking You.

    There are many reasons why xmlString could be not well formed. There is no magic recipe for making it well formed: just look at it and see why it is not parseable.
    Note that this line:
    String xmlString = baos.toString();can be problematic if you have non ASCII-7 characters in your XML document. baos could then contain a byte representation of these characters in one particular encoding, but, since you use the .toString() method that relies on the default encoding of your system, you can end up with a mismatch and garbage in your XML.

  • How to convert xml String to xml file?

    Hi,
    I got a method that do the following:
    public static String convertXmlToString(String xmlFileName) throws Exception
            File file = new File(xmlFileName);
            FileInputStream insr = new FileInputStream(file);
            byte[] fileBuffer = new byte[(int)file.length()];
            insr.read(fileBuffer);
            insr.close();
            return new String(fileBuffer);
         }The return String is the contents of an existing xml file and one example is shown below:
    <object type="server.WOXReference" id="0"><field name="actualPathObj"><object type="java.lang.String" id="1">C:\restClient\actualXMLObjects\812856084.xml</object></field><field name="object"><object type="server.WOXConstructor" id="2"><field name="className"><object type="java.lang.String" id="3">rec.SimpleRecognizer</object></field><field name="types"><array type="java.lang.String" length="3" id="4"><object type="java.lang.String" id="5">double[].class</object><object type="java.lang.String" id="6">double.class</object><object idref="6" /></array></field><field name="args"><array type="java.lang.Object" length="3" id="7"><array type="double" length="5" id="8">22.33 33.22 33.33 22.0 11.0</array><object type="java.lang.Double" id="9">2.2</object><object type="java.lang.Double" id="10">3.3</object></array></field><field name="retType"><object type="java.lang.String" id="11">act</object></field></object></field></object>
    and I want to change the above string to xml file like below:
    <object type="server.WOXReference" id="0"><field name="actualPathObj"><object type="java.lang.String" id="1">C:\restClient\actualXMLObjects\812856084.xml</object></field><field name="object"><object type="server.WOXConstructor" id="2"><field name="className"><object type="java.lang.String" id="3">rec.SimpleRecognizer</object></field><field name="types"><array type="java.lang.String" length="3" id="4"><object type="java.lang.String" id="5">double[].class</object><object type="java.lang.String" id="6">double.class</object><object idref="6" /></array></field><field name="args"><array type="java.lang.Object" length="3" id="7"><array type="double" length="5" id="8">22.33 33.22 33.33 22.0 11.0</array><object type="java.lang.Double" id="9">2.2</object><object type="java.lang.Double" id="10">3.3</object></array></field><field name="retType"><object type="java.lang.String" id="11">act</object></field></object></field></object>How to I change the above xml String back to xml file again? The appropriate tags must be taken care of like > must be > and < must be <.
    Please advice and can give me some sample code.
    Thanks.

    By writing some code that runs through the file and adds a new line for a new element using these methods here...
    http://java.sun.com/j2se/1.4.2/docs/api/org/xml/sax/ContentHandler.html
    i.e.
    startDocument()
    startElement(String namespaceURI, String localName, String qName, Attributes atts)
    endDocument()

  • Convert xml string into xml file?

    Hi,
    I got a method that returns an JDom Element object.
    Then I use the JDOM Element toString method() to change it into xml string.
    Now, I need to convert it into actual xml file.
    How to I do it?
    Thanks.

    Hi,
    If you got an xml string, just write it to an ordinary file. Look at FileWriter.
    /Kaj

  • From XML string to XML.

    Hi Guys,
             I have scenario wherein there is whole XML in a single element and i want to retrieve it to target XML structure. How do i do it?
    Source message is:
    <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
    - <SubmitBatchPwResponse xmlns="http://AltInn.no/webservices/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <SubmitBatchPwResult><?xml version="1.0"?> <b><DataBatchInReceipt schemaVersion="1.0" batchId="9e7d6e34-60b3-4c42-89f8-dce662913d3f" enterpriseSystemId="826" status="OK"><DataUnitInReceipt sendersReference="fd1fc4b6-ffee-47dd-aeee-d3d57b1d6b2e" submissionReference="{A07CD759-BC7C-4AC8-92BD-EE98D2CFD363}" status="OK" timeReceived="2006-10-11T14:16:14"><Message><MessageEntry type="Default" logged="2006-10-11T14:16:15">Sendt til Altinn</MessageEntry></Message></DataUnitInReceipt></DataBatchInReceipt></b></SubmitBatchPwResult>
      </SubmitBatchPwResponse>
    The target XSD is:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="DataUnitInReceipt">
    <xsd:annotation>
    <xsd:documentation>
    Status information per dataunit or attachment in a batch.
    </xsd:documentation>
    </xsd:annotation>
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="Message" minOccurs="0" form="qualified">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="MessageEntry" minOccurs="0" maxOccurs="unbounded" form="qualified">
    <xsd:annotation>
    <xsd:documentation>
    Additional information.This is usually a textual representation, but is XML representation for ValidationError messages
    </xsd:documentation>
    </xsd:annotation>
    <xsd:complexType>
    <xsd:sequence>
    <xsd:any namespace="##any" processContents="skip" />
    </xsd:sequence>
    <xsd:attribute name="type" use="required">
    <xsd:annotation />
    <xsd:simpleType>
    <xsd:restriction base="xsd:string">
    <xsd:enumeration value="Default" />
    <xsd:enumeration value="VersionError" />
    <xsd:enumeration value="GenericError" />
    <xsd:enumeration value="Recipient" />
    <xsd:enumeration value="AttachmentNotAllowedError" />
    <xsd:enumeration value="ValidationError" />
    <xsd:enumeration value="SubFormNotAllowedError" />
    <xsd:enumeration value="KID" />
    <xsd:enumeration value="EnterpriseSigningError" />
    <xsd:enumeration value="Received" />
    <xsd:enumeration value="SignedByParticipant" />
    <xsd:enumeration value="SignedByAccountant" />
    <xsd:enumeration value="DeletedWorkFlow" />
    <xsd:enumeration value="AddedWorkFlow" />
    <xsd:enumeration value="Archived" />
    </xsd:restriction>
    </xsd:simpleType>
    </xsd:attribute>
    <xsd:attribute name="logged" type="xsd:dateTime" use="required">
    <xsd:annotation />
    </xsd:attribute>
    </xsd:complexType>
    </xsd:element>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    </xsd:sequence>
    <xsd:attribute name="sendersReference" use="required">
    <xsd:annotation>
    <xsd:documentation>
    Unique id for the data on the original senders side. Must be unique within the system id.
    </xsd:documentation>
    </xsd:annotation>
    <xsd:simpleType>
    <xsd:restriction base="xsd:string">
    <xsd:minLength value="1" />
    </xsd:restriction>
    </xsd:simpleType>
    </xsd:attribute>
    <xsd:attribute name="submissionReference" use="required">
    <xsd:annotation>
    <xsd:documentation>
    This is the identification of the initial storage of the dataunit or attachment. This is globally unique within AltInn
    </xsd:documentation>
    </xsd:annotation>
    <xsd:simpleType>
    <xsd:restriction base="xsd:string">
    <xsd:minLength value="1" />
    </xsd:restriction>
    </xsd:simpleType>
    </xsd:attribute>
    <xsd:attribute name="workflowReference" type="xsd:string">
    <xsd:annotation>
    <xsd:documentation>
    Identification of the dataunit or attachment when submittet to the worflow module. This is globally unique within AltInn.
    </xsd:documentation>
    </xsd:annotation>
    </xsd:attribute>
    <xsd:attribute name="archiveReference" type="xsd:string">
    <xsd:annotation>
    <xsd:documentation>
    Identification of the dataunit or attachment when submittet to the archive. This is globally unique within AltInn.
    </xsd:documentation>
    </xsd:annotation>
    </xsd:attribute>
    <xsd:attribute name="receiversReference" type="xsd:string">
    <xsd:annotation>
    <xsd:documentation>
    Identification of the dataunit or attachment from the reciever of the data. The uniqueness of this reference cannot be guaranteed.
    </xsd:documentation>
    </xsd:annotation>
    </xsd:attribute>
    <xsd:attribute name="status" type="xsd:string" use="required">
    <xsd:annotation>
    <xsd:documentation>
    Status of the dataunit. The possible statuses are given in the documentation. The status may be supplemented by the message element.
    </xsd:documentation>
    </xsd:annotation>
    </xsd:attribute>
    <xsd:attribute name="timeReceived" use="required" />
    </xsd:complexType>
    </xsd:element>
    <xsd:element name="DataBatchInReceipt">
    <xsd:annotation>
    <xsd:documentation>
    Container for the receipts in a batch.
    </xsd:documentation>
    </xsd:annotation>
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="Message" type="xsd:string" minOccurs="0" form="qualified">
    <xsd:annotation>
    <xsd:documentation>
    Additional information accompanying the status
    </xsd:documentation>
    </xsd:annotation>
    </xsd:element>
    <xsd:element ref="DataUnitInReceipt" maxOccurs="unbounded" />
    </xsd:sequence>
    <xsd:attribute name="schemaVersion" type="xsd:decimal" use="required">
    <xsd:annotation>
    <xsd:documentation>
    Corresponding schema version
    </xsd:documentation>
    </xsd:annotation>
    </xsd:attribute>
    <xsd:attribute name="batchId" use="required">
    <xsd:annotation>
    <xsd:documentation>
    Unique id of the batch within the scope of the enterpriseSystemId.
    </xsd:documentation>
    </xsd:annotation>
    <xsd:simpleType>
    <xsd:restriction base="xsd:string">
    <xsd:minLength value="1" />
    <xsd:maxLength value="50" />
    </xsd:restriction>
    </xsd:simpleType>
    </xsd:attribute>
    <xsd:attribute name="enterpriseSystemId" type="xsd:int" use="required">
    <xsd:annotation>
    <xsd:documentation>
    Unique id of the system sending data. This id is obtained from registering the system with AltInn
    </xsd:documentation>
    </xsd:annotation>
    </xsd:attribute>
    <xsd:attribute name="status" use="required">
    <xsd:annotation>
    <xsd:documentation>
    Status of the batch as a whole. The status may be Ok even though individual statuses of dataunits are not Ok. The possible statuses are given in the documentation. The status may be supplemented by the message element.
    </xsd:documentation>
    </xsd:annotation>
    <xsd:simpleType>
    <xsd:restriction base="xsd:string">
    <xsd:enumeration value="OK" />
    <xsd:enumeration value="AccessDenied" />
    <xsd:enumeration value="FormatError" />
    <xsd:enumeration value="ValidationError" />
    <xsd:enumeration value="AllreadyExists" />
    <xsd:enumeration value="DoesNotExist" />
    <xsd:enumeration value="GenericError" />
    <xsd:enumeration value="InternalError" />
    <xsd:enumeration value="SigningAuthenticationError" />
    <xsd:enumeration value="SigningAuthorisationError" />
    <xsd:enumeration value="SigningOptionError" />
    <xsd:enumeration value="VirusDetected" />
    <xsd:enumeration value="DuplicateDataUnit" />
    <xsd:enumeration value="AuthorizationFailed" />
    </xsd:restriction>
    </xsd:simpleType>
    </xsd:attribute>
    </xsd:complexType>
    </xsd:element>
    </xsd:schema>
    Pls advice on how to go about this.
    Regards
    Ashish

    Hi Ashish,
    As usual use our XSLT mapping to do it, its pretty simple using XSLT. But you can also achieve this with other mappings but XSLT is simple for this kind of job. Can you post the target structure in XML format. So that it will be easy for us to help you in XSLT.
    Thanks,
    Prakash

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

  • Parse xml string not file

    Hi
    Can anyone help me I am trying to parse a xml file that is in a StringBuffer and not a file.
    Any suggestions would be great.
    Thanks ;>

    You can create a StringReader object from your StringBuffer. Once you have a StringReader object, you can create an InputSource object. Then, you can parse the InputSource with a DocumentBuilder object. I enclosed the code to illustrate. The method printXml is only used to check that the XML string is properly parsed and retrieved.
    import java.io.IOException;
    import java.io.StringReader;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Attr;
    import org.w3c.dom.Document;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    public class Parsing
        public static void main(String[] args)
         StringBuffer yourStringBuffer = new StringBuffer("<message>"
                                        +"<header>This is the message's header</header>"
                                        + "<body>This is the message's body</body>"
                                        + "</message>");
         try {
             DocumentBuilderFactory docBuilderFactory = new org.apache.crimson.jaxp.DocumentBuilderFactoryImpl();
             //throws ParserConfigurationException
             DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
             StringReader strReader = new StringReader(yourStringBuffer.toString());
             //throws SAXException, IOException, IllegalArgumentException
             Document doc = docBuilder.parse(new InputSource(strReader));
             System.out.println(printXml(doc)); //check if the XML can be retreived, i.e. it has been parsed successfully
         catch(ParserConfigurationException ex) {
             ex.printStackTrace();        
         catch(SAXException ex) {
             ex.printStackTrace();
         catch(IOException ex) {
             ex.printStackTrace();
         catch(IllegalArgumentException ex) {
             ex.printStackTrace();
        //Convenient method to print a Document object.
        public static String printXml(Document xmlDoc)
         StringBuffer xml = new StringBuffer("************ Xml Document *************");
         print(xmlDoc,xml);
         return xml.toString();
        protected static void print(Node node, StringBuffer strXml)
         int type;
         String elementName;
         Node childNode;
         NamedNodeMap attrs;
         Attr attrib;
         NodeList childNodes;
         strXml.append(System.getProperty("line.separator"));
         if(node == null)
             return;
         type = node.getNodeType();
         switch (type) {
         case Node.DOCUMENT_NODE: {
             print(((Document)node).getDocumentElement(),strXml); //recursive call to browse the tree
             break;
         case Node.ELEMENT_NODE: {
             elementName = node.getNodeName();
             strXml.append("<" + elementName);
             attrs = node.getAttributes();
             if(attrs == null)
              strXml.append(">");
             else {
              for(int i = 0; i < attrs.getLength(); i++) {
                  attrib = (Attr) attrs.item(i);
                  strXml.append(" " + attrib.getName() + "=\"" + attrib.getValue() + "\"");
              strXml.append(">");
             childNodes = node.getChildNodes();
             if(childNodes == null) return;
             for (int i = 0; i <  childNodes.getLength(); i++) {
              childNode = childNodes.item(i);
              if(childNode.getNodeType() == Node.TEXT_NODE)
                  strXml.append(childNode.getNodeValue());
              else
                  print(childNode,strXml);
             strXml.append(System.getProperty("line.separator"));
             strXml.append("</" + elementName + ">");
    }Hope this helps.

  • Extracting elements from an xml string - org.apache.xerces.dom.DeferredText

    Hello all,
    I am new to xml, and I thought I had a handle on things until I got this problem...I am getting an xml string from the body of an e-mail message, and then I am trying to extract elements out of it. Here is an example xml string:
    <?xml version="1.0" encoding="UTF-8"?>
    <filterRoot>
       <filter action="MOVE" bool="AND" name="My Saved Filter" target="Deleted Items">
          <condition attribute="TO" bool="AND" contains="CONTAINS">
             <value>[email protected]</value>
             <value>[email protected]</value>
             <value>[email protected]</value>
             <value>[email protected]</value>
             <value>[email protected]</value>
          </condition>
       </filter>
    </filterRoot>I am trying to extract the <filter> element out and store it into a Vector of Elements (called, not surprisingly, filters). However, I am getting a class cast exception:
    java.lang.ClassCastException: org.apache.xerces.dom.DeferredTextImplIt is being called from where I trying to extract the <filter> in this way:
            filterRoot = doc.getDocumentElement(); // get topmost element
            NodeList list = filterRoot.getChildNodes();
            Vector newFilters = new Vector();
            debug("There are "+list.getLength()+" filters in document");
            for(int i=0; i<list.getLength(); i++) {
                Node n = list.item(i);
                debug("Node "+i+" getNodeValue() is "+n.getNodeValue());
                Element temp = (Element)n;
                newFilters.add(temp);
            }Perhaps my question is, how do I correctly get hold of the <filter> node so that I may cast it as an Element?
    thanks,
    Riz

    Yes, I already knew that it is not a bug.
    But, I got next step problem.
    I put "false" to "include-ignorable-whitespace" feature in xerces parser.
    But, I still found unnecessary TextNodes in my parser object.
    Feature link : http://xerces.apache.org/xerces-j/features.html.
    I use xerces-2_8_0.
    DOMParser parser = new DOMParser();
    parser.setFeature("http://apache.org/xml/features/dom/include-ignorable-whitespace", false);
    parser.parse(inputSource);
    document = ps.getDocument();
    System.out.println(document.getDocumentElement().getChildNodes().length()); // still wrong lengthIs tehre any example of usage this feature?
    What is default defination of white-space "\n "(enter with one space) or " "(juz white space) or something else?
    Thanks,

  • Error after transforming xml string

    I have an XML string that I have to parse and update (transformer)
              String ji = "<book><person><first>p</first><last>m</last><age>22</age></person><person><first>b</first><last>g</last><age>46</age></person><person><first>s</first><last>j</last><age>40</age></person></book>";
              ByteArrayInputStream str = new ByteArrayInputStream(ji.getBytes());
                   DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
                   Document doc = docBuilder.parse(str);
                   doc.getDocumentElement().normalize();
                   str.reset();
                   ByteArrayOutputStream bos = new ByteArrayOutputStream();
                   NodeList listOfPersons = doc.getElementsByTagName("person");
                             int total = listOfPersons.getLength();
                             for(int i = 0; i < total; i++)
                                  Node firstpersonnode = listOfPersons.item(i);
                                  if(firstpersonnode.getNodeType() == Node.ELEMENT_NODE)
                                       Element firstPersonElement = (Element)firstpersonnode;
                                       NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
                                       Element firstNameElement = (Element)firstNameList.item(0);
                                       NodeList textFNList = firstNameElement.getChildNodes();
                                       Text t = (Text) textFNList.item(0);
                                       String p = t.toString();
                                       System.out.println("First Name : " +p);
                                       t.setData("sdasdsa");
                                       //String q = t.toString();
                                       //response.write("First Name : " +q);
                                       NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
                                       Element lastNameElement = (Element)lastNameList.item(0);
                                       NodeList textLNList = lastNameElement.getChildNodes();
                                       System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim());
                                       NodeList ageList = firstPersonElement.getElementsByTagName("age");
                                       Element ageElement = (Element)ageList.item(0);
                                       NodeList textAgeList = ageElement.getChildNodes();
                                       System.out.println("Age : " + ((Node)textAgeList.item(0)).getNodeValue().trim());
    I then write the ByteArrayOutputStream to an OutputStream becoz I need it in that format for the Transformer.
    oos = bos;
    str.reset();
    Source source = new DOMSource(doc);
    Result res = new StreamResult(oos);
    Transformer x = TransformerFactory.newInstance().newTransformer();
    x.transform(source,res);
    System.out.println("now the string is = "+oos.toString());
    Which Transforms it:
    Now my output is the Old XML string + some xml declaration + the Updated XML string.
    First Name : p
    Last Name : m
    Age : 22
    First Name : b
    Last Name : g
    Age : 46
    First Name : s
    Last Name : j
    Age : 40
    now the string is = <book><person><first>p</first><last>m</last><age>22</age></person><person><first>b</first><last>g</last><age>46</age></person><person><first>s</first><last>j</last><age>40</age></person></book><?xml version="1.0" encoding="utf-8"?>
    <book><person><first>sdasdsa</first><last>m</last><age>22</age></person><person><first>sdasdsa</first><last>g</last><age>46</age></person><person><first>sdasdsa</first><last>j</last><age>40</age></person></book>
    I only need to update the string

    Clap... here is the compilable code complete:
    Tried to make it shorter...:
    public class TestXML {
         public static void main(String[] args) {
              String ji = "<book><person><first>p</first><last>m</last><age>22</age></person><person><first>b</first><last>g</last><age>46</age></person><person><first>s</first><last>j</last><age>40</age></person></book>";
              ByteArrayInputStream str = new ByteArrayInputStream(ji.getBytes());
              ByteArrayOutputStream os=null;
              OutputStream oos = null;
              try
                   DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder docBuilder =  documentBuilderFactory.newDocumentBuilder();
                   Document doc = docBuilder.parse(str);
                   doc.getDocumentElement().normalize();
                   str.reset();
                   ByteArrayOutputStream bos = new ByteArrayOutputStream();
                   NodeList listOfPersons = doc.getElementsByTagName("person");
                             int total = listOfPersons.getLength();
                             for(int i = 0; i < total; i++)
                                  Node firstpersonnode = listOfPersons.item(i);
                                  if(firstpersonnode.getNodeType() == Node.ELEMENT_NODE)
                                       Element firstPersonElement =  (Element)firstpersonnode;
                                       NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
                                       Element firstNameElement = (Element)firstNameList.item(0);
                                       NodeList textFNList = firstNameElement.getChildNodes();
                                       Text t = (Text) textFNList.item(0);
                                       String p = t.toString();
                                       System.out.println("First Name : " +p);
                                       t.setData("sdasdsa");
                                                                     NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
                                       Element lastNameElement = (Element)lastNameList.item(0);
                                       NodeList textLNList = lastNameElement.getChildNodes();
                                       System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim());
                                       NodeList ageList = firstPersonElement.getElementsByTagName("age");
                                       Element ageElement = (Element)ageList.item(0);
                                       NodeList textAgeList = ageElement.getChildNodes();
                                       System.out.println("Age : " +   ((Node)textAgeList.item(0)).getNodeValue().trim());
                   byte b;
                   while ((b =(byte) str.read()) != -1) {
                        bos.write(b);
                   oos = bos;
                                            str.reset();
                             Source source = new DOMSource(doc);
                             Result res = new StreamResult(oos);
                             Transformer x =  TransformerFactory.newInstance().newTransformer();
                             x.transform(source,res);
                             System.out.println("now the string is = "+oos.toString());
         catch(Exception e){System.out.println(e);}
    }The o/p is as I mentioned in my first post
    Message was edited by:
    PremPrem
    Message was edited by:
    PremPrem

  • Error transforming XML string

    I have an XML string that I have to parse and update (transformer)
              String ji = "<book><person><first>p</first><last>m</last><age>22</age></person><person><first>b</first><last>g</last><age>46</age></person><person><first>s</first><last>j</last><age>40</age></person></book>";
              ByteArrayInputStream str = new ByteArrayInputStream(ji.getBytes());
                   DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder docBuilder =  documentBuilderFactory.newDocumentBuilder();
                   Document doc = docBuilder.parse(str);
                   doc.getDocumentElement().normalize();
                   str.reset();
                   ByteArrayOutputStream bos = new ByteArrayOutputStream();
                   NodeList listOfPersons = doc.getElementsByTagName("person");
                             int total = listOfPersons.getLength();
                             for(int i = 0; i < total; i++)
                                  Node firstpersonnode = listOfPersons.item(i);
                                  if(firstpersonnode.getNodeType() == Node.ELEMENT_NODE)
                                       Element firstPersonElement =  (Element)firstpersonnode;
                                       NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
                                       Element firstNameElement = (Element)firstNameList.item(0);
                                       NodeList textFNList = firstNameElement.getChildNodes();
                                       Text t = (Text) textFNList.item(0);
                                       String p = t.toString();
                                       System.out.println("First Name : " +p);
                                       t.setData("sdasdsa");
                                       //String q = t.toString();
                                       //response.write("First Name : " +q);
                                       NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
                                       Element lastNameElement = (Element)lastNameList.item(0);
                                       NodeList textLNList = lastNameElement.getChildNodes();
                                       System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim());
                                       NodeList ageList = firstPersonElement.getElementsByTagName("age");
                                       Element ageElement = (Element)ageList.item(0);
                                       NodeList textAgeList = ageElement.getChildNodes();
                                       System.out.println("Age : " +   ((Node)textAgeList.item(0)).getNodeValue().trim());
                             }I then write the ByteArrayOutputStream to an OutputStream becoz I need it in that format for the Transformer.
    oos = bos;
    str.reset();
                             Source source = new DOMSource(doc);
                             Result res = new StreamResult(oos);
                             Transformer x = TransformerFactory.newInstance().newTransformer();
                             x.transform(source,res);
                             System.out.println("now the string is = "+oos.toString());
    Which Transforms it:
    Now my output is the Old XML string + some xml declaration + the Updated XML string.
    First Name : p
    Last Name : m
    Age : 22
    First Name : b
    Last Name : g
    Age : 46
    First Name : s
    Last Name : j
    Age : 40
    now the string is = <book><person><first>p</first><last>m</last><age>22</age></person><person><first>b</first><last>g</last><age>46</age></person><person><first>s</first><last>j</last><age>40</age></person></book><?xml version="1.0" encoding="utf-8"?>
    <book><person><first>sdasdsa</first><last>m</last><age>22</age></person><person><first>sdasdsa</first><last>g</last><age>46</age></person><person><first>sdasdsa</first><last>j</last><age>40</age></person></book>I only need to update the string

    I have an XML string that I have to parse and update (transformer)
              String ji = "<book><person><first>p</first><last>m</last><age>22</age></person><person><first>b</first><last>g</last><age>46</age></person><person><first>s</first><last>j</last><age>40</age></person></book>";
              ByteArrayInputStream str = new ByteArrayInputStream(ji.getBytes());
                   DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder docBuilder =  documentBuilderFactory.newDocumentBuilder();
                   Document doc = docBuilder.parse(str);
                   doc.getDocumentElement().normalize();
                   str.reset();
                   ByteArrayOutputStream bos = new ByteArrayOutputStream();
                   NodeList listOfPersons = doc.getElementsByTagName("person");
                             int total = listOfPersons.getLength();
                             for(int i = 0; i < total; i++)
                                  Node firstpersonnode = listOfPersons.item(i);
                                  if(firstpersonnode.getNodeType() == Node.ELEMENT_NODE)
                                       Element firstPersonElement =  (Element)firstpersonnode;
                                       NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
                                       Element firstNameElement = (Element)firstNameList.item(0);
                                       NodeList textFNList = firstNameElement.getChildNodes();
                                       Text t = (Text) textFNList.item(0);
                                       String p = t.toString();
                                       System.out.println("First Name : " +p);
                                       t.setData("sdasdsa");
                                       //String q = t.toString();
                                       //response.write("First Name : " +q);
                                       NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
                                       Element lastNameElement = (Element)lastNameList.item(0);
                                       NodeList textLNList = lastNameElement.getChildNodes();
                                       System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim());
                                       NodeList ageList = firstPersonElement.getElementsByTagName("age");
                                       Element ageElement = (Element)ageList.item(0);
                                       NodeList textAgeList = ageElement.getChildNodes();
                                       System.out.println("Age : " +   ((Node)textAgeList.item(0)).getNodeValue().trim());
                             }I then write the ByteArrayOutputStream to an OutputStream becoz I need it in that format for the Transformer.
    oos = bos;
    str.reset();
                             Source source = new DOMSource(doc);
                             Result res = new StreamResult(oos);
                             Transformer x = TransformerFactory.newInstance().newTransformer();
                             x.transform(source,res);
                             System.out.println("now the string is = "+oos.toString());
    Which Transforms it:
    Now my output is the Old XML string + some xml declaration + the Updated XML string.
    First Name : p
    Last Name : m
    Age : 22
    First Name : b
    Last Name : g
    Age : 46
    First Name : s
    Last Name : j
    Age : 40
    now the string is = <book><person><first>p</first><last>m</last><age>22</age></person><person><first>b</first><last>g</last><age>46</age></person><person><first>s</first><last>j</last><age>40</age></person></book><?xml version="1.0" encoding="utf-8"?>
    <book><person><first>sdasdsa</first><last>m</last><age>22</age></person><person><first>sdasdsa</first><last>g</last><age>46</age></person><person><first>sdasdsa</first><last>j</last><age>40</age></person></book>I only need to update the string

Maybe you are looking for

  • Can't install or uninstall the latest version of iTunes

    Everytime I go to install the latest version of iTunes I get through most of it, then a window comes up that says "Windows Installer" - "The feature you are trying to use is on a network resource that is unavailable." - "Click OK to try again, or ent

  • Set Date/Currency/Numeric Format in WebIntelligence - Regional Settings

    We have migrated from BOE R2 to BOE R3.1, and our users have observed that the date & numeric format is not localized to spanish (Spain). How can Web Intelligence regional settings be configured to all the users (not editing personal configuration of

  • MDX Script for adding to column values

    Hi Experts, I am new in ASO MDX, need some help. I have one ASO out line in which I want to fetch addition of "Sales Tax" and "Income Tax" where as there are some other taxes also in "Total Tax". I want to fetch only the sum of "Sales Tax" AND "Incom

  • Does the Export Address book work also with Mavericks ?

    I want to export my address book to excel file ? Does the Exporter address book for mac was tested with MACOSX Maverick ? Is it going to work ?

  • Is the CALL LOG feature GONE???!?!?!?!?!?

    Someone PLEASE, PLEASE, PLEASE tell me that BB did not remove the CALL LOG feature (that was on the Torch)!  This is HORRIBLE!!!  If I wanted a phone that did not allow me to be productive, I would have activated my iPhone!!! PLEASE BRING THE CALL LO