How to parse whole xml elements into a java String

hello everybody,
I am trying to parse whole xml into a string for example
my xml file is as below:
<root>
    <element>
       <data id="1">1</data>
    </element>
    <element>
       <data id="2">2</data>
    </element>
</root>
in java whole data should be transfered as
String xmlString ="<root><element><data id=\"1\">1</data></element><element><data id=\"2\">2</data></element></root>";or in a simple way can xml be copied into a string? any assistance ...
thanQ in Advance.
Han.

This code is to convert xml document to a string.
                         try {
                              javax.xml.transform.TransformerFactory tfactory = TransformerFactory.newInstance();
                              javax.xml.transform.Transformer xform = tfactory.newTransformer();
                              javax.xml.transform.Source src = new DOMSource(xmlString);
                              java.io.StringWriter writer = new StringWriter();
                              StreamResult result = new javax.xml.transform.stream.StreamResult(writer);
                              xform.transform(src, result);
                              //System.out.println(writer.toString());          
                         } catch (TransformerConfigurationException e) {
                              e.printStackTrace();
                         }catch(Exception ex )
                              ex.printStackTrace();
                         }

Similar Messages

  • How Can One use XML data into our Java Program

    I have an Java Program and an XML file contaning data. I want to parse the xml data and use into my Java Program. How can I do so.

    Check out the org.xml.sax.XMLReader class.

  • How to read an XML file into a java program?

    hi,
    i want to load the following very simple xml file in my java program.
    <root>
    <weblogic>
    <url value="t3://192.168.1.160:7001" />
    <context value="weblogic.jndi.WLInitialContextFactory" />
    </weblogic>
    </root>
    I am getting the error: " Line=1: cvc-elt.1: Cannot find the declaration of element 'root'."
    What might be the problem can anyone help me out.
    My java class code is:
    public class BIXMLReader {
    /** All output will use this encoding */
    static final String outputEncoding = "UTF-8";
    // Parses an XML file and returns a DOM document.
    // If validating is true, the contents is validated against the DTD
    // specified in the file.
    public static Document parseXmlFile(String filename, boolean validating) {
    try {
    // Create a builder factory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setIgnoringComments(false);
    factory.setIgnoringElementContentWhitespace(false);
    factory.setCoalescing(false);
    factory.setValidating(validating);
    // Create the builder and parse the file
    System.out.println("filename = " + filename);
    DocumentBuilder db = factory.newDocumentBuilder();
    // Set an ErrorHandler before parsing
    OutputStreamWriter errorWriter = new OutputStreamWriter(System.err, outputEncoding);
    db.setErrorHandler(new MyErrorHandler(new PrintWriter(errorWriter, true)));
    Document doc = db.parse(new File(filename));
    System.out.println(doc.toString());
    return doc;
    } catch (SAXException e) {
    System.out.println("A parsing error occurred; the xml input is not valid. " + e.getMessage());
    } catch (ParserConfigurationException e) {
    System.out.println("Parser configuration exception has occured");
    } catch (IOException e) {
    System.out.println("IO Exception has occured " + e.getMessage());
    return null;
    // Error handler to report errors and warnings
    private static class MyErrorHandler implements ErrorHandler {
    /** Error handler output goes here */
    private PrintWriter out;
    MyErrorHandler(PrintWriter 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);
    }

    ok thanks, i can get the elements, but why did it not validate it?
    I want to read the child nodes of "weblogic" not by their name but by their index. Because i dont want to confine the reader so i want to read all the child nodes of weblogic (looping over them). i m doing the following but its not returning me the correct result and giving me the wrong count of child nodes.
    Element elementNode = (Element)doc.getElementsByTagName("weblogic").item(0);
    NodeList nodeList = elementNode.getChildNodes();
    int length = nodeList.getLength();
    System.out.println("length = "+ length); // the length its giving is 5 but i shuld get only 2
    for(int i=0; i < length; i++) {
    Element elmChild = (Element) nodeList.item(i);
    System.out.println(elmChild.getAttribute("value"));
    what might be the problem?

  • How to import an XML element into a loop parameter is XSL

    Hi,
    We are using XSL template to generate output in a pdf format. The input in an XML file. In the XSL we have a loop. Currently the initial and final value of the loop counter is hardcoded in the xsl file.
    <xsl:call-template name="forloop">
         <xsl:with-param name="i">1</xsl:with-param>
         <xsl:with-param name="count">6</xsl:with-param>
    </xsl:call-template>
    Down below we are using
         <xsl:template name="forloop">
              <xsl:param name="i"/>
              <xsl:param name="count"/>
              <xsl:if test="$i &lt;=$count">
                   <fo:table-row>
                   <xsl:call-template name="forloop">
                        <xsl:with-param name="i">
                             <xsl:value-of select="$i + 1"/>
                        </xsl:with-param>
    etc, etc.
    Query :
    Currently the final value of the loop is hardcoded to 6. I want to set its value based of an element BAR_CODE_PRINT_NUM value (which can be either 0 or 6) of the XML File.
    <LIST_G_BAR_CODE_PRINT>
    <G_BAR_CODE_PRINT>
    <BAR_CODE_PRINT>Y</BAR_CODE_PRINT>
    <BAR_CODE_PRINT_NUM>6</BAR_CODE_PRINT_NUM>
    </G_BAR_CODE_PRINT>
    </LIST_G_BAR_CODE_PRINT>
    Can anyone please tell me how this is to be done. I have tried the following but it did not work.
    Approach 1 :
    <xsl:if test="LIST_G_BAR_CODE_PRINT/G_BAR_CODE_PRINT/BAR_CODE_PRINT_NUM &gt; 3">
         <xsl:with-param name="count">6</xsl:with-param>
    </xsl:if>
    <xsl:if test="LIST_G_BAR_CODE_PRINT/G_BAR_CODE_PRINT/BAR_CODE_PRINT_NUM &lt; 3">
         <xsl:with-param name="count">0</xsl:with-param>
    </xsl:if>
    Approach 2 :
    <xsl:with-param name="count"><xsl:value-of disable-output-escaping="no" select="LIST_G_BAR_CODE_PRINT/G_BAR_CODE_PRINT/BAR_CODE_PRINT_NUM"/>
    </xsl:with-param>
    Thanks

    I have managed to resolve it. It was a problem with the nesting of the attribute. The following worked
    <xsl:with-param name="count"><xsl:value-of disable-output-escaping="no" select="/NUMNEWJOBCARD/LIST_G_BAR_CODE_PRINT/G_BAR_CODE_PRINT/BAR_CODE_PRINT_NUM"/></xsl:with-param>
    Thanks

  • How do I get the proper UTF-8 NVARCHAR2 DB Value into a Java String?

    Hello, I have a mixed char 8.1.7 database with UTF-8 as my NLS
    charset. I used SQL Worksheet to enter test polish unicode
    characters 50309,50310... into an NVARCHAR2 column using
    insert...char(nnn using NCHAR_CS) and get the following result
    from DUMP(columnname,1016):
    Typ=1 Len=12 CharacterSet=UTF8:
    c4,85,c4,86,c4,87,c4,88,c4,89,c4,8a.
    Everything looks good.
    Now, how do I get them out into a Java String and verify that I
    have received the correct hex codes?
    I have tried:
    1. CHAR lChr = OracleResultSet.getCHAR(ColumnName, csUTF8); or
    and lChr.characterStreamValue();
    2. InputStream lIStr = arsResultSet.getBinaryStream(ColumnName);
    3. String lStr = (String)arsResultSet.getObject(ColumnName);
    and then:
    lStr.getBytes("UTF-8"); or lStr.toCharArray();
    I always get questions marks and negative byte values or the
    values: 261,262,263,264,265,266.
    I am using the latest 9.0.1. JDBC Thin drivers and the Oracle
    extensions: OracleResultSet, OracleStatement etc...
    Please let me know what class/method I need, to get the Oracle
    NVARCHAR2 unicode string from the result set into a Java string
    and what method to use to look at the underlying hex codes.
    TIA for any pointers.

    If I use in bdInt=sc.nextInt();a substring cannot be used.
    Does anyone know how I solve this question without substring? Perhapse something I've mentioned above
    sincerely h

  • How to parse thus XML data?

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

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

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

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

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

  • How to import a XML file into the document?

    Hai,
    i had created a table using xml file....
    Now i want to import that xml file tabel into the document...
    Can any one tell me how to import the xml file into the document?
    thanks
    senthil

    Hai...
    this is senthil...
    i'm beginner for creating adobe indesign plugins..
    i want to import a html file in the document...
    i want to create a table by using html tags and
    that table will be imported into the document..
    How shall i do it?
    can any one plzz explain me?

  • How to parse a XML file

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

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

  • Moving an existing xml element into aTable

    Hi Everyone,
    After importing the xml I need to place or convert the xml elements into the table. Is there any way to do this by JS?
    Here is the sample Table xml elements....
    <table-wrap id="ch3_t1">
    <label>Table 3.1</label>
    <caption>
    <title>Anatomy and Classification of Major Hepatic Resections</title>
    </caption>
    <table>
    <thead>
    <tr>
    <th align="left" valign="top" colspan="5">Anatomic Classification</th>
    </tr>
    <tr>
    <th align="left" valign="top">Couinaud</th>
    <th align="left" valign="top" colspan="2">Goldsmith and Woodburne</th>
    <th align="left" valign="top">Brisbane</th>
    <th align="left" valign="top">Segments resected</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td align="left" valign="top">Right hepatectomy</td>
    <td align="left" valign="top" colspan="2">Right hepatic lobectomy</td>
    <td align="left" valign="top">Right hemihepatectomy</td>
    <td align="left" valign="top">V, VI, VII, VIII</td>
    </tr>
    <tr>
    <td align="left" valign="top">Right lobectomy<sup>a</sup>
    </td>
    <td align="left" valign="top" colspan="2">Extended right hepatic lobectomy</td>
    <td align="left" valign="top">Right trisectionectomy</td>
    <td align="left" valign="top">IV,V,VI, VII, VIII<sup>b</sup>
    </td>
    </tr>
    <tr>
    <td align="left" valign="top">Left hepatectomy</td>
    <td align="left" valign="top" colspan="2">Left hepatic lobectomy</td>
    <td align="left" valign="top">Left hemihepatectomy</td>
    <td align="left" valign="top">II, III, IV</td>
    </tr>
    <tr>
    <td align="left" valign="top">Extended left hepatectomy<sup>a</sup>
    </td>
    <td align="left" valign="top" colspan="2">Extended left lobectomy</td>
    <td align="left" valign="top">Left lateral sectionectomy</td>
    <td align="left" valign="top">II, III, IV, V, VIII<sup>b</sup>
    </td>
    </tr>
    <tr>
    <td align="left" valign="top">Left lobectomy</td>
    <td align="left" valign="top" colspan="2">Left lateral segmentectomy</td>
    <td align="left" valign="top">Left trisectionectomy</td>
    <td align="left" valign="top">II, III</td>
    </tr>
    </tbody>
    </table>
    </table-wrap>
    Looking forward your replies... Your help will be thankful....

    You may want to look again, specifically section 20.11 Moving Oracle Enterprise Content Management to a Production System, Task 4.
    The same basic steps would apply to 10g, minus the WebLogic parts. (Also note that prior to 11g, what you are attempting is really a non-supported configuration. In 11g, Oracle at least gives this set of supported pointers.)

  • How to move some xml element and its content to a new frame

    Hi All,
    How to move some xml element and its content to a new frame.

    Hi Chinnadk,
    Sorry my code its comment some lines. Now only I check the forum thread, you just try one more time.
    #target InDesign;
    #include "/Program Files (x86)/Adobe/Adobe InDesign CS5.5/Scripts/XML Rules/glue code.jsx"
    var myDoc = app.activeDocument;
    //____________________ XML RULE SET
    var myRuleSet = new Array (new margintag);
    with(myDoc){
        var elements = xmlElements;
        __processRuleSet(elements.item(0), myRuleSet);
    function margintag(){
        this.name = "margintag";
        //this.xpath = "//margintag[@type='mn2']";
        this.xpath = "//margintag";
        this.apply = function(myElement, myRuleProcessor){
            with(myElement){
                app.select(myElement);
                try{
                    var myPrePara = app.selection[0].paragraphs[-1].parentTextFrames[0].paragraphs.previousItem(app.selection[0].paragraphs[-1]);
                    if(myPrePara.characters[-1].contents=="\r"){
                        myPrePara.characters[-1].remove();
                    var myTextframe = myElement.placeIntoInlineFrame(["7p9","6p"]);
                    myTextframe.appliedObjectStyle= myDoc.objectStyles.item("MN1");
                    myTextframe.fit(FitOptions.FRAME_TO_CONTENT);
                    myTextframe.parentStory.paragraphs.everyItem().appliedParagraphStyle = app.activeDocument.paragraphStyles.itemByName("MN1");
                    }catch(e){}
                app.selection = null;
            return true;
    thx,
    csm_phil

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

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

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

  • How to parse nested xml file using dom

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

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

  • How to pass a JavaScript variable into a java method

    I would like to know how to pass a JavaScript variable into a java method with in a <% %> tag inside a JSP file like so:
    <%@ page contentType="text/html;charset=windows-1252"%>
    <html>
    <head>
    <script LANGUAGE="JavaScript">
    myValue = someDynamicValue;
    <% System.out.println(myValue)%>
    </script>
    </head>
    <body>
    </body>
    </html>
    obviously "System.out.println(myValue)" will not work because myValue is seen as a java variable and not a JavaScript variable.
    I would like to know how to let the jsp file, that I wrote in the above code, see myValue as a JavaScript variable and not a java variable so that I can pass it to a java method.
    NOTE: the java method does not have to be a println() method, it can be any method of my choice.
    NOTE: someDynamicValue is a JavaScript value that can dynamically change

    I don't believe you can. JSPs are really just elaborate templates that an engine such as Tomcat parses and generates an HTML page based on. That page is then displayed to the user. By the time you want to use some function in Javascript, the JSP has already been parsed and generated.
    Basically, Javascript and JSPs can't talk to each other. One's server-side and the other is client-side.

  • How to map javax.xml.datatype.XMLGregorianCalendar to java.util.Calendar

    Hi ,
    How to map javax.xml.datatype.XMLGregorianCalendar to java.util.Calendar so that i can use pass String parameter in YYYY-MM-DD format to my Web service.
    I generated the schema classes using Jaxb 2.1.5.
    Please give suggestion
    Thanks in Advance.

    toGregorianCalendar().getTime()

Maybe you are looking for

  • "Go to song" doesn't work.

    I'm playing an MP3 that is in my iTunes library. iTunes is playing it. I click on the tiny little arrow so I can get to "Go to song" so iTunes will show it in the Music view. I select that and it does nothing. Sooooo, I go to the playlist "Recently p

  • Email link pops up window in IE

    I have selected text and used the mailto:[email protected] link to create an email link. I have tried static text and dynamic text and in IE, the mail client pops up, but so does an annoying window with "Navigation to Website was cancelled". It seems

  • Planning Book...

    Hi friends, I have a requirement in which i need to read data from the planning Book in Advanced Planning and Optimization System. Can anyone provide me the "Bapi for reading data of planning book". Useful replies will be rewarded. Thanx, Rahul.

  • Help need to embed jsp on flex

    hi, i m trying to build jsp application on flex, by keeping flex as the base. i want to navigate to jsp application for flex and i m using spring at the server side. could any one help me on this. thnks in advance.

  • Initializing array of objects

    This is my beginning effort to initialize an array of objects, but the compiler messages seem to lead me astray. What is the easiest way to do this, or can't it be done in a manner similar to this? Do I have to do it from a program loop or something?