Jdom parsing

hi iam new to java and jdom parsing.my imput is user passes the xml file and a string (string is not a tag in xml its a attribute value).i need to look for the string in the xml file and get all its child attributes .my xml looks like
<Trs>
     <cetTra>
            <xName>"jeff"</xName>
                     <child>pat</child>
                     <child>sush</childT>
                     <Delay>
                <timeSec>60</timeSec>
                <retry>1</retry>
      </Delay>
        </cetTra>
      <cetTra>
            <xName>"kumsa"</xName>
                     <child>sac</child>
                     <child>ed</child>
                     <Delay>
                <timeSec>5</timeSec>
                <retry>10</retry>
      </Delay>
        </cetTra>
  </Trs>my quesion is how to get only the the contents based on attribute .Input string will be jeff i need to get the contents only for jeff .my code looks like
List passedStringList = root.getChildren("Cetra");
Iterator i = passedStringList.iterator();
      while (i.hasNext()) {
        Element serv= (Element) i.next();
        out.print("\t" + serv.getChild("xName")
                                .getText());o/p gets both jeff and kumsa
Thanks for the help

XML file has an error at <child>sush</childT>. It should be </child>
Since jdom uses SAX structure, devise a recursive depth search function similar to listChildren() in http://www.cafeconleche.org/books/xmljava/chapters/ch14s08.html . It contains examples on jdom as well. Test whether current object returned by iterator is an instance of Element. and content is "jeff".
if ( child.getContent().equalsIgnoreCase("\"jeff\"") )Then invoke listChildren() once again with current Element object as start point. Manipulate print statements to suit your need.

Similar Messages

  • JDOM: Parsing XML String, getting error

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

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

  • JDOM parser fails to parse Huge Size Xml Files ??? Unable to Parse ???

    Hi All,
    When i transformed or parsed many XML Files of huge size...I am getting java.lang.OutOfMemory error for all the huge xml files. It is working fine for files which is of small size.
    I've 2GB ram in my system. I have also set heapsize for the JVM.
    -Xms512M -Xmx1800M (or) -Xms512M -Xmx1500M
    I like to know what are the drawbacks of JDOM parser ?
    What is the maximum size of the Xml which JDOM can parse ?
    I've read a long time before that parsers have certain limitations. Can anybody tell me the limitations of the parses?
    Please help. i'm currently using jdom.jar to parse the xml files.
    Thanks,
    J.Kathir

    Hi All,
    When i transformed or parsed many XML Files of huge
    size...I am getting java.lang.OutOfMemory error for
    all the huge xml files. It is working fine for files
    which is of small size.Of course it is.
    >
    I've 2GB ram in my system. I have also set heapsize for the JVM.
    -Xms512M -Xmx1800M (or) -Xms512M -Xmx1500MYou can't always get what you want. Your JVM is competing with all the other processes on your machine, including the OS, for RAM.
    I like to know what are the drawbacks of JDOM parser ?You just discovered it: all DOM parsers create an in-memory representation of the entire document. A SAX parser does not.
    What is the maximum size of the Xml which JDOM can parse ?The max amount of memory that you have available to you.
    I've read a long time before that parsers have
    certain limitations. Can anybody tell me the
    limitations of the parses?See above.
    Please help. i'm currently using jdom.jar to parse the xml files.You can try a SAX parser or a streaming parser. Maybe those can help.
    %

  • How do I get values from a resultset using JDOM?

    I am very new to this and I dont have the slightest idea how to retrive values from a result and create a XML tree using JDOM
    Can someone please help me?
    I have the JDOM Parser installed on my machine.
    This is my code so far:
    import org.jdom.input.*;
    import org.jdom.*;
    import java.sql.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Display extends HttpServlet {
    public void doPost(HttpServletRequest rq, HttpServletResponse rs) throws IOException, ServletException
    rs.setContentType("text/html");
    PrintWriter out = rs.getWriter();
    try {
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection listcars_con = DriverManager.getConnection("jdbc:odbc:Cars");
         Statement listcars_statement = listcars_con.createStatement();
         ResultSet listcars_rs = listcars_statement.executeQuery("Select CarNr FROM cars");
    //Load the appropriate driver, establish a connection and create a statement which is used to execute the query that returns all the
    //columns from the cars table
    Document doc = new Document(new Element("rootElement"));
              listcars_statement.close();
              listcars_con.close();
    //close the connections
    catch (ClassNotFoundException cnfe)
    System.err.println(cnfe);
    } catch (SQLException sqlex) {
    System.err.println(sqlex);
    } catch (Exception er) {
    er.printStackTrace();
    } //closing bracket for doPost method
    } //closing bracket for class definition

    ResultSet object has nothing to do with XML... so the only way to it
    is just read each row/column in your resultset and then create
    XML record based on structure of your resultset - annoying job...
    Also you can try to use tool developed by Oracle which based
    on SQL select statement parses resultset into XML...
    Paul

  • Can I leverage JDom or Dom4J for java mapping in PI 7.0?

    Hi,
    since we know that PI 7.0 is based on jdk1.4 which officially allows DOM and SAX,but could I using the open source API like JDom or Dom4J via importing the related jar file to PI IR for java mapping?Anyone tried that?

    Hi ,
             I tried importing jar files into PI7.0 I was able to do so.
    First add the external jar file for JDOM into build path in eclipse (or NWDS). I did this in eclipse.
    Again I tried to import the same jar file into project within eclipse. Then the jar file will be broken into class files.
    Now compile the JDOM code you wrote and do project ->build all. This will generate the class file for your source code in addition to the class files formed earlier. Now exit from eclipe. Move to source folder of the eclipse. there you will find the .java file and the set of class files which were imported into the project earlier. Copy these files to separete folder say "myclass". Now again move to "bin" folder of your eclipse settings and obtain the .class file for the source code you have written. Copy this class file to the  "myclass" folder. Now using WINZIP zip all files into one ZIP file within "myclass" folder. Finally import this ZIP into PI 7.0 server. Run the mapping code using test tab. If you are getting any linkage error then you need to obtain correct external jar for JDOM parser else the mapping should run fine.
    Regards
    Anupam

  • Xmlparsercover fails to parse supplied family.xml

    I have downloaded the XML parser for PLSQL and installed it as
    per the instructions. However, when try to execute the supplied
    Domsample, providing the supplied family.xml, I get 'Error
    occurred while parsing' error, following by the full path name of
    the error file I have supplied.
    I have checked the installation carefully and have confirmed that
    I am passing in full file paths but to no avail.
    I have tried asimplied piece of PL/SQL, documented below, which
    as can be seen is falling over in the same way.
    What has been missed ?
    The error is coming back from the Java class that implements
    Xmlparsercover.parse so I cannot investigate any further as do
    not have the source.
    declare
    err varchar2(512);
    p xmlparser.parser;
    begin
    p := xmlparser.newparser;
    xmlparser.setvalidationmode(p,FALSE);
    xmlparser.seterrorlog(p,
    '/u06/home/dev22c/ghicks/xml_for_plsql/sample/error.txt');
    xmlparser.setbasedir(p,
    '/u06/home/dev22c/ghicks/xml_for_plsql/sample');
    xmlparsercover.parse(p.ID
    ,'/u06/home/dev22c/ghicks/xml_for_plsql/sample/family.xml'
    ,err);
    -- now print out the returned error
    dbms_output.put_line (err);
    end;
    On running the above file the following value is printed out
    for the contents of err :
    /u06/home/dev22c/ghicks/xml_for_plsql/sample/error.txt
    I can confirm that the directory called sample in which the
    file family.xml resides and to which the file error.txt is meant
    to be written has full privileges granted on it. The file
    error.txt does not exist prior to running the above and is not
    created by the above.
    Basically, I need someone in the Oracle XML team to look at the
    source code in Java and tell me under what circumstances the
    returned err code can be set to the full pathname of the error
    file. This may then give a further clue as to the problem.
    null

    Hi All,
    When i transformed or parsed many XML Files of huge
    size...I am getting java.lang.OutOfMemory error for
    all the huge xml files. It is working fine for files
    which is of small size.Of course it is.
    >
    I've 2GB ram in my system. I have also set heapsize for the JVM.
    -Xms512M -Xmx1800M (or) -Xms512M -Xmx1500MYou can't always get what you want. Your JVM is competing with all the other processes on your machine, including the OS, for RAM.
    I like to know what are the drawbacks of JDOM parser ?You just discovered it: all DOM parsers create an in-memory representation of the entire document. A SAX parser does not.
    What is the maximum size of the Xml which JDOM can parse ?The max amount of memory that you have available to you.
    I've read a long time before that parsers have
    certain limitations. Can anybody tell me the
    limitations of the parses?See above.
    Please help. i'm currently using jdom.jar to parse the xml files.You can try a SAX parser or a streaming parser. Maybe those can help.
    %

  • XML parser for fatching multiple values from XML

    Hi,
    In my scenirio i have to facth multiple values from XML file and then set in to Table in webdynpro...
    Fo example my xml has values like...
    <xml>
         <item>
              <item1>
                   <quantity>
                        100
                   </quantity>
                   <price>
                        50
                   </price>
              </item1>
              <item2>
                   <quantity>
                        200
                   </quantity>
                   <price>
                        20
                   </price>
              </item2>
              <item3>
                   <quantity>
                        300
                   </quantity>
                   <price>
                        10
                   </price>
              </item3>
         </item>
    </xml>
    then i have to fcath those quantity and price and set in to table...
    How to do taht in webdynpro and does any one have parser code for retriving multiple values...

    Hi,
    1) You need to use JDOM parser.
    2) The code for parsing XML using JDOM parser is readily available if you search on google.
    3) You will have to check the attribute during every parsing and then if attribute is quantity you can fetch the corresponding tags.
    4) Something similar to this:
    org.jdom.Document document = parser.build(file);
                    org.jdom.Element rootElement = document.getRootElement();
                    org.jdom.Element childElement = rootElement.getChild("file");
                    Element xmlElement = childElement.getChild("item");
                    if (xmlElement != null) {
                        List itemElementsList = xmlElement.getChildren("item1");
                        if (itemElementsList != null) {
                            Iterator iterator3 = itemElementsList.iterator();
                            while (iterator3.hasNext()) {
                                //For each group get quantity
                                Element itemElement = (Element) iterator3.next();
                                List quantityElementsList =
                                        itemElement.getChildren("quantity");
                                if (quantityElementsList != null) {
                                    Iterator iterator2 =
                                            quantityElementsList.iterator();
                                    while (iterator2.hasNext()) {
    // Your code                                                                               
    You might need to make some changes as per your rquirement. Just use this sample to understand how you need to parse the xml
    Hope it helps.
    Regards.
    Rajat
    Edited by: Rajat Jain on Jan 22, 2009 9:51 AM

  • IllegalException :JDOM comment: Comment data cannot start with a hyphen

    This morning i noticed that JDOM cannot read a XML document that has a comment with syntax <!-- -. If you look closer i have 3 hyphens instead of 2 which is the normal syntax of a comment begining.
    But my fate, i ended up having a big XML file with comments all over the document like this
    <!-- -============ Browse ======================= -->
    Watching this comment there is a space followed by a 3rd hyphen. Don't know why the document owner did like this.
    I was looking for a better way to do a search and replace of the <!-- - to <!-- before i open the document for JDOM parsing. Coming from C# world, i know there is a XMLDocument doc = new XMLDocument() class where we can load a file in memory and do some edits and save the document. Is there any API like that in Java, and whats the best search replace strategy?
    Any help would be appreciated.

    -su option starts the JDeveloper in single user mode. The system directory will be created inside the JDev installation itself (as opposed to the normal - Documents and Settings folder).
    You don't need to start the JDev with that option always. That suggestion was because you were getting the error.
    As far as the error is concerned, I believe it is something to do with space in folder - "Documents and settings". You might want to check out that registry entry NtfsDisable8dot3NameCreation again. My guess is, you would've set the registry entry before the installation, but you might need to restart the machine after setting that registry entry to take effect. And then could've started the installation.
    -Arun

  • End Element Using JDOM

    Hi All,
    Can we find out the end element using org.jdom parser..........like suppose we have a element node like this...........
    <Node abc=def>ghi</Node>
    I want to find out the </Node> Tag............
    I need this very urgently...............Thanx in advance............

    This is a fun situation actually. Let's assume you have:
    Element parentElement;
    Element elementToAdd;
    Element elementToAddItAfter;Now, one of the cute features of JDOM (some consider it ugly but it's good for solving this problem) is that all the getChildren methods return 'live lists'. This means if you modify the list, you modify the underlying list.
    // Get all the children.  This is a live list.
    List children = getChildren();
    // Find the index of the element to add the new element after.
    int index = children.indexOf(elementToAddItAfter);
    // Add the new element to the next index along.
    // This does cover the case where indexOf returned -1.
    children.add(index + 1);The JDOM tree should update with the new child having been inserted exactly after the other one.
    Hope this helps. ^_^

  • Input and Output Stream conversion

    I have problem. In my application I should change OutputStream to InputStream and vv. I try to explain it using easy example.
    I am creatin xml document and using XMLOutputter (I am using org.jdom parser) I could write it to file using FileOutputStream, but first I'd like to encrypt this file. For that reason I need InputStream. I write this file on disc, next i read this file, encrypt and write again and at last delete the unencrypted file. Could do It without writeing unencrypted file on disc? Maybe using only streams? Pleas help me, how to do it. Maybe I should convert OutputStream to InputStream.
    When I reading information from encrypted file I have the same problem - streams conversion.

    I wrote an article about how to convert an OutputStream to an InputStream. You can read the article at:
    http://ostermiller.org/convert_java_outputstream_inputstream.html
    It discusses three methods for conversion: byte arrays, piped streams, and circular buffers.

  • Problem while reading special characters in java

    Hi i am faving the follwing xml.
    <ns1:dc_application_bullets>
    <w:p wsp:rsidR="004E4084" wsp:rsidRPr="007024E6" wsp:rsidRDefault="000D5B97" wsp:rsidP="007024E6">
    <w:r>
    <w:rPr>
    <w:rFonts w:ascii="Arial Unicode MS" w:fareast="Arial Unicode MS" w:h-ansi="Arial Unicode MS" w:cs="Arial Unicode MS" w:hint="fareast" />
    <wx:font wx:val="Arial Unicode MS" />
    <w:lang />
    </w:rPr>
    <w:t>������</w:t>
    </w:r>
    </w:p>
    </ns1:dc_application_bullets>
    no i ma trying to parse this XML using java program and jdom parser. when i try to read the special chacters and print then i ma getting ?? on the console.
    how can i print on to the console as the one what they look.
    any help is appreciated.

    please any bosy throw some light on this.You first. Do you think we're mindreaders? Reading and printing code please.

  • How2 create xml & ent  files from JAVA? (xml that gets data from ent file)

    Is there any API that can make it easy?
    * For parsing XML I use JDOM parser
    I want to create file like this:
    XML file: some.xml
    <?xml version="1.0"?>
    <!DOCTYPE xfat [
    <!ENTITY  d_request SYSTEM  "some.ent">
    ]>
    <!--
    /home/bNUMBER/Programs/XFAT/runxfat some.xml
    -->
    <xfat title = 'Fat Title (some) '>
    <database  filename = 'Some_Data/some.xml'/>
    <snc  filename  = "../snc/snc.xml"/>
    <configuration sp = '../sp/some_only.xml' name='Some_A-H'>
       &d_request;
    </configuration>
    </xfat>and ent file:
    <ddef title    = 'some d def title (some)'>
         <dcalc  snc    = '7_A9'
                meas   = 'm73'
                red    = 'GOOD' binval='MCMS' lug='YES'/>
    </ddef>

    has anyone idea what to search?

  • XPATH in a XML Document

    Hi guys, I need again your help.
    I have many xml documents and I need create a class that "search" data at this xml documents. What I can do this!?!?
    For example, I wanna get the Paul ages in the age.xml document!!!!! I wanna create a method like this:
    SearchXmlfile search = new SearchXmlFile();
    String result = search.get("/person@age[person@attribute = 'paul']"); //I pass the xpath like parameter
    Someone know What I can do this?!!?
    Just another question. When I create a transformer I set the Source and Result "Objects" (SAX, DOM or Stream). And where i set the xsl file?!!? I am reading the jwsdp tutorial and I don't understand where I configure the xsl file transformer to the transformer object!!!!
    Thanks Again.
    Giscard.

    1. For selecting nodes with an XPath expression parse with the JDom parser and select nodes with the XPath class.
    http://www.jdom.org/
    2. Set the stylesheet in the Transformer.
               DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
               Document document = builder.parse(new File("c:/input.xml"));
                TransformerFactory tFactory =
                    TransformerFactory.newInstance();
                StreamSource stylesource = new StreamSource(stylesheet);//Set the Stylesheet
                Transformer transformer = tFactory.newTransformer(stylesource);
                DOMSource source = new DOMSource(document);
                StreamResult result = new StreamResult(System.out);
                transformer.transform(source, result);

  • Joboss throws OutOfmemory Error

    sir / madam,
    I am using jdom parser for parsing my XML file .I can get correct results when the xml files are small.But when my xml file grows to larger in size it shows ' java.lang.OutOfMemoryError' .How can I solve this problem.If U have some sample code with no such error will be very helpfull for me.
    My XML file contains 3laks lines
    [email protected]
    JINOY.P.L

    You could try and increase the heap size of the VM running the code in question using the following java command line option, -Xmx
    See the J2SE docs for more details.
    http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/java.html#options

  • Building XML from fragments

    Here's my scenario:
    I have multiple PL/SQL stored functions that return REF CURSORs. Each REF CURSOR contains information to build a portion of an XML document. I want to assemble these XML "fragments" into a DOM object, then apply a stylesheet to the entire object before saving it to a table.
    All of this will be done in Java, and I need to make it efficient (in terms of speed and memory) since the XML document may grow to be very large. What is the best way to go about doing this?
    Right now, I'm able to call getXMLDOM() which returns a complete XML document for each fragment, but what should I do with it now? Does anyone have any suggestions on what my next step should be?

    SetDocType is available only in JDOM parser. I would like to know is it prossible without that.
    Thanks !!

Maybe you are looking for

  • IPhoto crashes when ordering large, hardcover book!  iLife 11

    Can anyone help? I spent many hours creating a book as a Christmas gift and when I try to order it iphoto "quits unexpectedly" after approx. page 50. I saw another thread about deleting something in keychain, quitting all other applications and dragg

  • Preview fails to quit

    I have run MacOSX 10.2.8 (Jaguar) on my iBook successfully for years. Suddenly, Preview has developed an intractable fault. Preview will not open any files yet fails to quit. Finder won't force quit Preview either. In the Force Quit window Preview ap

  • FaceTime problem. Help!

    Hello, Apple buddies. Please help me. I am not able to open my FaceTime account in my iPad . Apple is saying that I'd is already in use. I had changed my password but still, I am not able to do so. I want to first disable my FaceTime account. Help!

  • Can't install more RAM, what will help?

    OK need a bit of help. My elderly iMac has been a bit problematic lately, spinning beach balls, laggy, that chuggy noise which I always think is Spotlight indexing... (can't think of a more technical way to describe it!). I've just nosed around and s

  • Unable to customize control bar.  Control-Click does not produce drop down window.

    I just downloaded Logic Pro X (10.0.7) on a Macbook Pro, OSX 10.9.4, 2.3 Core i7 with 8 GB Ram.  I'm trying to customize the control bar (to add auto punch).  According to "help" the control bar is customized by Control-Clicking on the control bar an