How to parse XML to Java object... please help really stuck

Thank you for reading this email...
If I have a **DTD** like:
<!ELEMENT person (name, age)>
<!ATTLIST person
     id ID #REQUIRED
>
<!ELEMENT name ((family, given) | (given, family))>
<!ELEMENT age (#PCDATA)>
<!ELEMENT family (#PCDATA)>
<!ELEMENT given (#PCDATA)>
the **XML** like:
<person id="a1">
<name>
     <family> Yoshi </family>
     <given> Samurai </given>
</name>
<age> 21 </age>
</person>
**** Could you help me to write a simple parser to parse my DTD and XML to Java object, and how can I use those objects... sorry if the problem is too basic, I am a beginner and very stuck... I am very confuse with SAXParserFactory, SAXParser, ParserAdapter and DOM has its own Factory and Parser, so confuse...
Thank you for your help, Yo

Hi, Yo,
Thank you very much for your help. And I Wish you are there...I'm. And I plan to stay - It's sunny and warm here in Honolulu and the waves are up :)
A bit more question for dear people:
In the notes, it's mainly focus on JAXB,
1. Is that mean JAXB is most popular parser for
parsing XML into Java object? With me, definitely. There are essentially 3 technologies that allow you to parse XML documents:
1) "Callbacks" (e.g. SAX in JAXP): You write a class that overrides 3 methods that will be called i) whenever the parser encounters a start tag, ii) an end tag, or iii) PCDATA. Drawback: You have to figure out where the heck in the document hierarchy you are when such a callback happens, because the same method is called on EACH start tag and similarly for the end tag and the PCDATA. You have to create the objects and put them into your own data structure - it's very tedious, but you have complete control. (Well, more or less.)
2) "Tree" (e.g. DOM in JAXP, or it's better cousin JDOM): You call a parser that in one swoop creates an entire hierarchy that corresponds to the XML document. You don't get called on each tag as with SAX, you just get the root of the resulting tree. Drawback: All the nodes in the tree have the same type! You probably want to know which tags are in the document, don't you? Well, you'll have to traverse the tree and ask each node: What tag do you represent? And what are your attributes? (You get only strings in response even though your attributes often represent numbers.) Unless you want to display the tree - that's a nice application, you can do it as a tree model for JTree -, or otherwise don't care about the individual tags, DOM is not of much help, because you have to keep track where in the tree you are while you traverse it.
3) Enter JAXB (or Castor, or ...): You give it a grammar of the XML documents you want to parse, or "unmarshall" as the fashion dictates to call it. (Actually the name isn't that bad, because "parsing" focuses on the input text while "unmarshalling" focuses on the objects you get, even though I'd reason that it should be marshalling that converts into objects and unmarshalling that converts objects to something else, and not vice versa but that's just my opinion.) The JAXB compiler creates a bunch of source files each with one (or now more) class(es) (and now interfaces) that correspond to the elements/tags of your grammar. (Now "compiler" is a true jevel of a misnomer, try to explain to students that after they run the "compiler", they still need to compile the sources the "compiler" generated with the real Java compiler!). Ok, you've got these sources compiled. Now you call one single method, unmarshall() and as a result you get the root node of the hierarchy that corresponds to the XML document. Sounds like DOM, but it's much better - the objects in the resulting tree don't have all the same type, but their type depends on the tag they represent. E.g if there is the tag <ball-game> then there will be an object of type myPackage.BallGame in your data structure. It gets better, if there is <score> inside <ball-game> and you have an object ballGame (of type BallGame) that you can simply call ballGame.getScore() and you get an object of type myPackage.Score. In other words, the child tags become properties of the parent object. Even better, the attributes become properties, too, so as far as your program is concerned there is no difference whether the property value was originally a tag or an attribute. On top of that, you can tell in your schema that the property has an int value - or another primitive type (that's like that in 1.0, in the early release you'll have to do it in the additional xjs file). So this is a very natural way to explore the data structure of the XML document. Of course there are drawbacks, but they are minor: daunting complexity and, as a consequence, very steep learning curve, documentation that leaves much to reader's phantasy - read trial and error - (the user's guide is too simplicistic and the examples too primitive, e.g. they don't even tell you how to make a schema where a tag has only attributes) and reference manual that has ~200 pages full of technicalities and you have to look with magnifying glas for the really usefull stuff, huge number of generated classes, some of which you may not need at all (and in 1.0 the number has doubled because each class has an accompanying interface), etc., etc. But overall, all that pales compared to the drastically improved efficiency of the programmer's efforts, i.e. your time. The time you'll spend learning the intricacies is well spent, you'll learn it once and then it will shorten your programming time all the time you use it. It's like C and Java, Java is order of magnitude more complex, but you'd probably never be sorry you gave up C.
Of course the above essay leaves out lots and lots of detail, but I think that it touches the most important points.
A word about JAXB 1.0 vs. Early Release (EA) version. If you have time, definitively learn 1.0, they are quite different and the main advantage is that the schema combines all the info that you had to formulate in the DTD and in the xjs file when using the EA version. I suggested EA was because you had a DTD already, but in retrospect, you better start from scratch with 1.0. The concepts in 1.0 are here to stay and once your surmounted the learning curve, you'll be glad that you don't have to switch concepts.
When parser job is done,
what kind of Java Object we will get? (String,
InputStream or ...)See above, typically it's an object whose type is defined as a class (and interface in 1.0) within the sources that JABX generates. Or it can be a String or one of the primitive types - you tell the "compiler" in the schema (xjs file in EA) what you want!
2. If we want to use JAXB, we have to contain a
XJS-file? Something like:In EA, yes. In 1.0 no - it's all in the schema.
I am very new to XML, is there any simpler way to get
around them? It has already take me 4 days to find a
simple parser which give it XML and DTD, then return
to me Java objects ... I mean if that kind of parser
exists....It'll take you probably magnitude longer that that to get really familiar with JAXB, but believe me it's worth it. You'll save countless days if not weeks once you'll start developing serious software with it. How long did it take you to learn Java and it's main APIs? You'll either invest the time learning how to use the software others have written, or you invest it writing it yourself. I'll take the former any time. But it's only my opinion...
Jan

Similar Messages

  • How to program this in java? Please help

    How to program this in java?
    please explain steps, it has to come out like this:
    example
    input: 3b1w3b
    output:
    BBBWBBB

    import java.io.*;
    public class Test {
    static java.io.PrintStream o = java.lang.System.out;
    public static void main(String[] args)throws Exception {      
         BufferedReader BR = new BufferedReader(new InputStreamReader(System.in));
         System.out.print("Enter plot for printing: ");
         String s = BR.readLine();
         char[] cs = s.toLowerCase().toCharArray();
         for(int i=0, j=0; i < cs.length-0x1; i+=0x2, j=0)
              while(j++ < (int)(cs[i]-0x30))
                   o.print((char)(cs[i+0x1]-0x20));
    I tried changeing it to this so I can enter my own string, but I want to change it some more so that it can enter multiple input separated by space, so that it can form a sort of picture line by line. I tried using tolkenizer but I get errors. I dont know how to use tolkenizer properly can anyone please TEACH. you dont have to tell how or give me the code if you dont want to. yes I know Im a noob and I dont know java as good as everyone here, If everyone thinks I don't deserve help then DON'T help, I'm just trying to learn programming

  • How to get xml into java object

    yo
    i want to get the xml doc into some object like Document
    i have downloaded code:
    public class Echo extends org.xml.sax.helpers.DefaultHandler
    this class compiles fine but when i instantiate the class in code i get:
    "Exception in thread 'main' java.lang.NoClassDefFoundError: org/xml/sax/helpers/DefaultHandler"
    Please, what does this mean and how do i get this to recognise that i want to use a specific parser
    thanks a lot

    You are probably not specifying the XML jar files (xalan.jar & xerces.jar) on the run line. What is the command you are using?
    Actually, which "jars" you use is dependent on which version of the XML Java release you downloaded (Winter or Fall).

  • How to parse xml in java

    i wrote java client to invoke webservice(TIBCO) as a result i am getting back xml. now i have to parse xml and use the information. can anyone pls advise on this.
    thanks

    There are two kinds of parser available. One converts the XML to a Document Object Model (DOM). This is a heirarchy of Node objects each of which represents an element of XML, a tag, an attribute a piece of text etc.. Then you walk the graph extracting what you want.
    The other kind is the SAX event parser. You give this a callback (extends DefaultHandler) and it calls appropriate methods for each element as it's encountered.
    The second method is probably slight more complex to use but will deal with files of unlimited size without huge memory usage.
    In both cases you get the parser using a Factory/Interface pattern. You'll find the factory classes in javax.xml.parsers. The rest of the DOM stuff is in org.w3c.dom and the SAX stuff in org.xml.sax.

  • How to convert XML to Java Object

    Hello:
    I would like to convert an XML doucment into an object, but I having alot of trouble doing this.
    here is the document:
    <?xml version="1.0" encoding="UTF-8"?>
    <Marketing_Programs>
    <Marketing_Program>
    <rateCode type="String">A</rateCode>
    <plan type="String">AAA/CAA</plan>
    <flatRate type="double">0.0</flatRate>
    <discountRate type="double">10.0</discountRate>
    </Marketing_Program>
    <Marketing_Program>
    <rateCode type="String">B</rateCode>
    <plan type="String">Business Rate</plan>
    <flatRate type="double">0.0</flatRate>
    <discountRate type="double">5.0</discountRate>
    </Marketing_Program>
    </Marketing_Programs>
    A Marketing_Program class exists and so I want to create multiple Marketing_Program objects and store it in hashmap. I'm pretty much stuck on XML to object conversion due to lack of knowledge on converting string to the appropriate datatype.
    Any help would be greatly appreciated!
    Thanks in advance!
    Peter

    using jaxb, castor, jox...
    [email protected]

  • How to properly create path art object, please help

    Hello there,
    I have a vector of AIRealPoint , each point is actual X, Y coordinate of the stroke. I need to create path art object out of this vector.
    I'm  somehow confused how to correctly construct segments array form the given AIRealPoints, my goal is to have single path object where count of segments is equal to count of AIrealPoints first and last points are anchors. SDK documenation is not really helping here...
    Please, take a look at the code snippet, it seems I'm doing something wrong with in and out params of segment , in any case I fail to create simple path object ....
    ASErr CretaeVectorPathTest2(vector<AIRealPoint>& stroke)
    AIArtHandle artHandle;
    ASErr result = kNoErr;
    try {
      AIRealPoint start;
      long lngStrokeLength = stroke.size()-1;
      AIArtHandle lineHandle = NULL;
      AIErr error = sAIArt->NewArt( kPathArt, kPlaceAboveAll, NULL, &lineHandle );
      if ( error ) throw( error );
      error = sAIPath->SetPathSegmentCount( lineHandle, lngStrokeLength );
      if ( error ) throw( error );
      AIPathSegment *segment = new AIPathSegment[lngStrokeLength];
      // This is a first point of the path
      segment[0].p.h = stroke[0].h;
      segment[0].p.v = stroke[0].v;
      segment[0].in = segment[0].out = segment[0].p;
      segment[0].corner = true;
      for(inti=1 ;i< lngStrokeLength-1;i++)
       segment[i].p.h = stroke[i].h ;
       segment[i].p.v = stroke[i].h ;
       // NOT GOOD!!!
       segment[i].in.h  = stroke[i-1].h ;
       segment[i].in.v  = stroke[i-1].v ;
       segment[i].out.h  = stroke[i+1].h;
       segment[i].out.v  = stroke[i+1].v;
       segment[i].corner = false;
    // NOT GOOD!!!
      // This is a last point of the path
      segment[lngStrokeLength].p.h = stroke[lngStrokeLength].h;
      segment[lngStrokeLength].p.v = stroke[lngStrokeLength].v;
      segment[lngStrokeLength].in = segment[lngStrokeLength].out = segment[lngStrokeLength].p;
      segment[lngStrokeLength].corner = true;
      error = sAIPath->SetPathSegments( lineHandle, 0, lngStrokeLength, segment );
      if ( error ) throw( error );
      error = sAIPath->SetPathClosed( lineHandle, false );
      if ( error ) throw( error );
    // apply color width etc.
      AIPathStyle style;
      error = sAIPathStyle->GetPathStyle( lineHandle, &style );
      if ( error ) throw( error );
      style.strokePaint = true;
      style.stroke.color.kind = kFourColor;
      style.stroke.color.c.f.cyan = 0;
      style.stroke.color.c.f.magenta = 0;
      style.stroke.color.c.f.yellow = 0;
      style.stroke.color.c.f.black = 100;
      style.stroke.width = 0.75;
      style.stroke.dash.length = 0;
      delete[] segment;
      error = sAIPathStyle->SetPathStyle( lineHandle, &style );
      if ( error ) throw( error );
    catch (ai::Error& ex) {
      result = ex;
    return result;
    Thanks,
    David

    As for beziers, Illustrator uses cubic beziers which are fairly straight forward (thank goodness!). Here's a lift from Wikipedia's Bezier entry:
    This image is pretty good at demonstrating how AI's bezier segments work. In the animation, the moving point has two lines sticking off it, ending with two points. If P3 was an AISegment, the left-hand blue point would be in and the right-hand point would be out. If we were to translate the state of the animation in its last frame into AI code, you'd basically have something like this:
    AISegment segment1, segment2;
    segment1.p = p0;
    segment1.in = p0;
    segment1.out = p1;
    segment2.in = p2;
    segment2.p = p3;
    segment.out = p3;
    Note that this would imply any line that continues beyond either end point isn't a smooth beizer curve (i.e. the curve is limited to between these points). That effectively makes them corner points (I think). Also, the line formed by linking in & p or out & p is the tangent to the curve at p, which I think you can make out from from the animation.
    Another way to get a feel for this is to use the pen tool to draw a line with a few segments. If you then pick the sub-select tool (white selection arrow, not black selection arrow) and select individual points on the curve, you'll see when you do that two 'anchors' jut out from each point. Those are the in & out for that point on the curve.
    Its all a little confusing because technically, a bezier segment between p & q would be p, p.out, q.in & q. (four vertices). To avoid repeating information, and keep it simple for non-beziers, AI's segments are still the vertices. So if you wanted to make the nth segment a beizer, you'd need n & n+1 from AI's path, and you'd modify two-thirds of each AISegment (p, out from n & in, p from n+1).
    I hope that helps, but if you have any further questions, feel free to ask! If you need to do anything fancy with beziers, there are some helpful utilites in AIRealBezier.h.

  • How to parse xml data into java component

    hi
    everybody.
    i am new with XML, and i am trying to parse xml data into a java application.
    can anybody guide me how to do it.
    the following is my file.
    //MyLogin.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    class MyLogin extends JFrame implements ActionListener
         JFrame loginframe;
         JLabel labelname;
         JLabel labelpassword;
         JTextField textname;
         JPasswordField textpassword;
         JButton okbutton;
         String name = "";
         FileOutputStream out;
         PrintStream p;
         Date date;
         GregorianCalendar gcal;
         GridBagLayout gl;
         GridBagConstraints gbc;
         public MyLogin()
              loginframe = new JFrame("Login");
              gl = new GridBagLayout();
              gbc = new GridBagConstraints();
              labelname = new JLabel("User");
              labelpassword = new JLabel("Password");
              textname = new JTextField("",9);
              textpassword = new JPasswordField(5);
              okbutton = new JButton("OK");
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 5;
              gl.setConstraints(labelname,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 5;
              gl.setConstraints(textname,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 10;
              gl.setConstraints(labelpassword,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 10;
              gl.setConstraints(textpassword,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 15;
              gl.setConstraints(okbutton,gbc);
              Container contentpane = getContentPane();
              loginframe.setContentPane(contentpane);
              contentpane.setLayout(gl);
              contentpane.add(labelname);
              contentpane.add(labelpassword);
              contentpane.add(textname);
              contentpane.add(textpassword);
              contentpane.add(okbutton);
              okbutton.addActionListener(this);
              loginframe.setSize(300,300);
              loginframe.setVisible(true);
         public static void main(String a[])
              new MyLogin();
         public void reset()
              textname.setText("");
              textpassword.setText("");
         public void run()
              try
                   String text = textname.getText();
                   String blank="";
                   if(text.equals(blank))
                      System.out.println("First Enter a UserName");
                   else
                        if(text != blank)
                             date = new Date();
                             gcal = new GregorianCalendar();
                             gcal.setTime(date);
                             out = new FileOutputStream("log.txt",true);
                             p = new PrintStream( out );
                             name = textname.getText();
                             String entry = "UserName:- " + name + " Logged in:- " + gcal.get(Calendar.HOUR) + ":" + gcal.get(Calendar.MINUTE) + " Date:- " + gcal.get(Calendar.DATE) + "/" + gcal.get(Calendar.MONTH) + "/" + gcal.get(Calendar.YEAR);
                             p.println(entry);
                             System.out.println("Record Saved");
                             reset();
                             p.close();
              catch (IOException e)
                   System.err.println("Error writing to file");
         public void actionPerformed(ActionEvent ae)
              String str = ae.getActionCommand();
              if(str.equals("OK"))
                   run();
                   //loginframe.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    hi, thanks for ur reply.
    i visited that url, i was able to know much about xml.
    so now my requirement is DOM.
    but i dont know how to code in my existing file.
    means i want to know what to link all my textfield to xml file.
    can u please help me out. i am confused.
    waiting for ur reply

  • How to parse XML against XSD,DTD, etc.. locally (no internet connection) ?

    i've searched on how to parse xml against xsd,dtd,etc.. without the needs of internet connection..
    but unfortunately, only the xsd file can be set locally and still there needs the internet connection for the other features, properties.
    XML: GML file input from gui
    XSD: input from gui
    javax.xml
    package demo;
    import java.io.File;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.xml.XMLConstants;
    import javax.xml.transform.Source;
    import javax.xml.transform.stream.StreamSource;
    import javax.xml.validation.Schema;
    import javax.xml.validation.SchemaFactory;
    import javax.xml.validation.Validator;
    import org.xml.sax.SAXException;
    public class Sample1WithJavaxXML {
         public static void main(String[] args) {
              URL schemaFile = null;
              try {
                   //schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
                   File file0 = new File("AppSchema-C01-v1_0.xsd");
                   schemaFile = new URL(file0.toURI().toString());
              } catch (MalformedURLException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              //Source xmlFile = new StreamSource(new File("web.xml"));
              Source xmlFile = new StreamSource(new File("C01.xml"));
              SchemaFactory schemaFactory = SchemaFactory
                  .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
              //File file1 = new File("XMLSchema.dtd");
              //SchemaFactory schemaFactory = SchemaFactory
                   //.newInstance("javax.xml.validation.SchemaFactory:XMLSchema.dtd");
              Schema schema = null;
              try {
                   schema = schemaFactory.newSchema(schemaFile);
              } catch (SAXException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              Validator validator = schema.newValidator();
              try {
                validator.validate(xmlFile);
                System.out.println(xmlFile.getSystemId() + " is valid");
              } catch (SAXException e) {
                System.out.println(xmlFile.getSystemId() + " is NOT valid");
                System.out.println("Reason: " + e.getLocalizedMessage());
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    }Xerces
    package demo;
    import java.io.File;
    import java.util.Date;
    import org.apache.xerces.parsers.DOMParser;
    public class SchemaTest {
         private String xmlFile = "";
         private String xsdFile = "";
         public SchemaTest(String xmlFile, String xsdFile) {
              this.xmlFile = xmlFile;
              this.xsdFile = xsdFile;
         public static void main (String args[]) {
              File file0 = new File("AppSchema-C01-v1_0.xsd");
              String xsd = file0.toURI().toString();
              SchemaTest testXml = new SchemaTest("C01.xml",xsd);
              testXml.process();
         public void process() {
              File docFile = new File(xmlFile);
              DOMParser parser = new DOMParser();
              try {
                   parser.setFeature("http://xml.org/sax/features/validation", true);
                   parser.setFeature("http://apache.org/xml/features/validation/schema", true);
                   parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
                             xsdFile);
                   ErrorChecker errors = new ErrorChecker();
                   parser.setErrorHandler(errors);
                   System.out.println(new Date().toString() + " START");
                   parser.parse(docFile.toString());
              } catch (Exception e) {
                   System.out.print("Problem parsing the file.");
                   System.out.println("Error: " + e);
                   System.out.println(new Date().toString() + " ERROR");
                   return;
              System.out.println(new Date().toString() + " END");
    }

    Thanks a lot Sir DrClap..
    I tried to use and implement the org.w3c.dom.ls.LSResourceResolver Interface which is based on the SAX2 EntityResolver.
    please give comments the way I implement it. Here's the code:
    LSResourceResolver Implementation
    import org.w3c.dom.ls.LSInput;
    import org.w3c.dom.ls.LSResourceResolver;
    import abc.xml.XsdConstant.Path.DTD;
    import abc.xml.XsdConstant.Path.XSD;
    public class LSResourceResolverImpl implements LSResourceResolver {
         public LSResourceResolverImpl() {
          * {@inheritDoc}
         @Override
         public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
              ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
              LSInput input = new LSInputImpl(publicId, systemId, baseURI);
              if ("http://www.w3.org/2001/xml.xsd".equals(systemId)) {
                   input.setByteStream(classLoader.getResourceAsStream(XSD.XML));
              } else if (XsdConstant.PUBLIC_ID_XMLSCHEMA.equals(publicId)) {
                   input.setByteStream(classLoader.getResourceAsStream(DTD.XML_SCHEMA));
              } else if (XsdConstant.PUBLIC_ID_DATATYPES.equals(publicId)) {
                   input.setByteStream(classLoader.getResourceAsStream(DTD.DATATYPES));
              return input;
    }I also implement org.w3c.dom.ls.LSInput
    import java.io.InputStream;
    import java.io.Reader;
    import org.w3c.dom.ls.LSInput;
    public class LSInputImpl implements LSInput {
         private String publicId;
         private String systemId;
         private String baseURI;
         private InputStream byteStream;
         private String stringData;
         public LSInputImpl(String publicId, String systemId, String baseURI) {
              super();
              this.publicId = publicId;
              this.systemId = systemId;
              this.baseURI = baseURI;
         //getters & setters
    }Then, here's the usage/application:
    I create XMLChecker class (SchemaFactory implementation is Xerces)
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import javax.xml.XMLConstants;
    import javax.xml.stream.FactoryConfigurationError;
    import javax.xml.transform.Source;
    import javax.xml.transform.stream.StreamSource;
    import javax.xml.validation.Schema;
    import javax.xml.validation.SchemaFactory;
    import javax.xml.validation.Validator;
    import org.xml.sax.ErrorHandler;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import abc.xml.XsdConstant.Path.XSD;
    public class XMLChecker {
         private ErrorMessage errorMessage = new ErrorMessage();
         public boolean validate(String filePath){
              final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
              List<Source> schemas = new ArrayList<Source>();
              schemas.add(new StreamSource(classLoader.getResourceAsStream(XSD.XML_SCHEMA)));
              schemas.add(new StreamSource(classLoader.getResourceAsStream(XSD.XLINKS)));
              schemas.add(new StreamSource(classLoader.getResourceAsStream("abc/xml/AppSchema.xsd")));
              SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
              schemaFactory.setResourceResolver(new LSResourceResolverImpl());
              try {
                   Schema schema = schemaFactory.newSchema(schemas.toArray(new Source[schemas.size()]));
                   Validator validator = schema.newValidator();
                   validator.setErrorHandler(new ErrorHandler() {
                        @Override
                        public void error(SAXParseException e) throws SAXException {
                             errorMessage.setErrorMessage(e.getMessage());
                             errorMessage.setLineNumber(e.getLineNumber());
                             errorMessage.setColumnNumber(e.getLineNumber());
                             throw e;
                        @Override
                        public void fatalError(SAXParseException e) throws SAXException {
                             errorMessage.setErrorMessage(e.getMessage());
                             errorMessage.setLineNumber(e.getLineNumber());
                             errorMessage.setColumnNumber(e.getLineNumber());
                             throw e;
                        @Override
                        public void warning(SAXParseException e) throws SAXException {
                             errorMessage.setErrorMessage(e.getMessage());
                             errorMessage.setLineNumber(e.getLineNumber());
                             errorMessage.setColumnNumber(e.getLineNumber());
                             throw e;
                   StreamSource source = new StreamSource(new File(filePath));
                   validator.validate(source);
              } catch (SAXParseException e) {
                   return false;
              } catch (SAXException e) {
                   errorMessage.setErrorMessage(e.getMessage());
                   return false;
              } catch (FactoryConfigurationError e) {
                   errorMessage.setErrorMessage(e.getMessage());
                   return false;
              } catch (IOException e) {
                   errorMessage.setErrorMessage(e.getMessage());
                   return false;
              return true;
         public ErrorMessage getErrorMessage() {
              return errorMessage;
    }Edited by: erossy on Aug 31, 2010 1:56 AM

  • How to parse xml file in midlet

    Hi Guys,
    i wish to parse xml file and display it in my midlet. i found api's supporting xml parsing in j2se ie., in java.net or j2se 5.0. Can u please help me what package to use in midlet?
    how to parse xml info and display in midlet? Plz reply soon......Thanks in advance....

    i have exactly the same problem with KXml2, but using a j2me-polish netbeans project.
    i've tried to work around with similar ways like you, but none of them worked. now i've spent 3 days for solving this problem, i'm a bit disappointed :( what is wrong with setting the downloaded kxml2 jar path in libraries&resources?
    screenshot

  • Convert MBox into XML into Java Objects

    Hello all,
    this is a general question, i dont know weather there is such libs or not.
    However, please tell me what you know.
    i want to program a java application for searching purpose in Mbox.
    i thought its possible and easier to try to convert the emails from the MBox into XML files, and from these create java objects when i need or even convert the XML into html for viewing.
    Any suggestions are welcome.
    Also antoher solutions are greate.
    thanks in advance!
    Sako.

    I don't know what this MBox you speak of is - I assume it's not the thing I use to hook upa guitar to GarageBand. Maybe you mean it as a generic term for mailbox? The easiest solution (to my mind) would be to use a Java API provided by whatever MBox is. If there is no such thing, then if you get XML-formatted version of the messages I suppose writing code to parse the XML into Java Objects would be a good option if you wanted to do further manipulation of them, but if all you want to do is display them as HTML in a browser then just use XSLT to transform them.
    Good Luck
    Lee

  • How to parse xml (kXML)

    I have some problems when I try to parse xml with the kXML parser. My xml doc looks like this:
    <?xml version="1.0" encoding="utf-8" ?>
    - <dsGreenRoom>
    - <Rooms>
    - <RoomsInfo>
    <ID>1</ID>
    <Name>Rum 101</Name>
    <Type>Dubbelrum</Type>
    <NumberOfBeds>2</NumberOfBeds>
    <Rate>980,00</Rate>
    <Currency>SEK</Currency>
    <Description>Ett genomtrevligt rum</Description>
    </RoomsInfo>
    - <RoomsInfo>
    <ID>2</ID>
    <Name>Mellanrummet</Name>
    <Type>Enkelrum</Type>
    <NumberOfBeds>1</NumberOfBeds>
    <Rate>650,00</Rate>
    <Currency>SEK</Currency>
    <Description>Ett litet tr?ngt rum i mitten</Description>
    </RoomsInfo>
    - <RoomsInfo>
    <ID>3</ID>
    <Name>Rum 102</Name>
    <Type>Flerb?ddsrum</Type>
    <NumberOfBeds>3</NumberOfBeds>
    <Rate>1250,00</Rate>
    <Currency>SEK</Currency>
    <Description>Ett ?nnu trevligare rum</Description>
    </RoomsInfo>
    </Rooms>
    </dsGreenRoom>
    And my code looks like this:
    KXmlParser parser = new KXmlParser();
                   parser.setInput(is, null);
                   Document doc = new Document();
                   doc.parse(parser);          
                   int child_count = root.getChildCount();
                   System.out.println("child = " + child_count + "\n");
                   for (int i=0; i < child_count; i++) {
              if (root.getType(i) == Node.ELEMENT) {
                   Element kid = root.getElement(i);
                        System.out.println("kid = " + kid.getName());
                   int babies = kid.getChildCount();
                   System.out.println("babies = " + babies);
                   for (int j=0; j < babies; j++) {
                        if (kid.getType(j) == Node.ELEMENT) {
                             Element room = kid.getElement(j);
                             System.out.println("room.getType() = " + room.getType(j));
                        if (room.getName().equals("ID")) {
              System.out.println("elName.getName() = " + room.getName());
              System.out.println("elName.geText() = " + room.getText(j));
              else if (room.getName().equals("Name")) {
              System.out.println("elName.getName() = " + room.getName());
              System.out.println("elName.geText() = " + room.getText(j));
                   } // end for(int j...)
              } // end if (root.getType(i)
              } //for (int i...)
    The problem is that I don't know how to get the values out of the tags:
    <ID>1</ID>
    <Name>Rum 101</Name>
    <Type>Dubbelrum</Type>
    <NumberOfBeds>2</NumberOfBeds>
    <Rate>980,00</Rate>
    <Currency>SEK</Currency>
    <Description>Ett genomtrevligt rum</Description>
    It's no problem to get the value from the firsts i.e. <ID> but I don't know how to get the value from <Name> ... <Description>. I have looked att examples but I don't understand how to do this. Can someone please help me =)

    okay, sorry, I only read the half of your problem ;-)
    You can read the content using the getText(0) method. the 0 indicates the number of the children which you want to get. That is always a 0 because you have always just one text-children in your text-tags. The content is again a children of type text!
    hth
    Kay

  • How to Parse XML into String in BPEL?

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

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

  • JAXB and inheritance. Converting xml to java object

    I have a schema "FreeStyle.xsd" i used JAXB to generate POJO's . I get around 15 classes. I have a config.xml which is compliant to this schema . Now i want to write a java program which takes the config.xml and converts it into a java object . Please anybody help me with this . Thanks in advance
    Freestyle.xsd
    <?xml version="1.0" encoding="windows-1252"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="FreeStyleProject" type="hudson.model.FreeStyleProject"/>
    <xsd:complexType name="hudson.model.FreeStyleProject">
      <xsd:complexContent>
       <xsd:extension base="hudson.model.Project">
        <xsd:sequence/>
       </xsd:extension>
      </xsd:complexContent>
    </xsd:complexType>
    <xsd:complexType name="hudson.model.Project">
      <xsd:complexContent>
       <xsd:extension base="hudson.model.BaseBuildableProject">
        <xsd:sequence/>
       </xsd:extension>
      </xsd:complexContent>
    </xsd:complexType>
    <xsd:complexType name="hudson.model.BaseBuildableProject">
      <xsd:complexContent>
       <xsd:extension base="hudson.model.AbstractProject">
        <xsd:sequence/>
       </xsd:extension>
      </xsd:complexContent>
    </xsd:complexType>
    <xsd:complexType name="hudson.model.AbstractProject">
      <xsd:complexContent>
       <xsd:extension base="hudson.model.Job">
        <xsd:sequence>
         <xsd:element name="concurrentBuild" type="xsd:boolean"/>
         <xsd:element name="downstreamProject" type="hudson.model.AbstractProject"
                      minOccurs="0" maxOccurs="unbounded"/>
         <xsd:element name="scm" type="hudson.scm.SCM" minOccurs="0"/>
         <xsd:element name="upstreamProject" type="hudson.model.AbstractProject"
                      minOccurs="0" maxOccurs="unbounded"/>
        </xsd:sequence>
       </xsd:extension>
      </xsd:complexContent>
    </xsd:complexType>
    <xsd:complexType name="hudson.scm.SCM">
      <xsd:sequence>
       <xsd:element name="browser" type="hudson.scm.RepositoryBrowser"
                    minOccurs="0"/>
       <xsd:element name="type" type="xsd:string" minOccurs="0"/>
      </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="hudson.scm.RepositoryBrowser">
      <xsd:sequence/>
    </xsd:complexType>
    <xsd:complexType name="hudson.model.Job">
      <xsd:complexContent>
       <xsd:extension base="hudson.model.AbstractItem">
        <xsd:sequence>
         <xsd:element name="buildable" type="xsd:boolean"/>
         <xsd:element name="build" type="hudson.model.Run" minOccurs="0"
                      maxOccurs="unbounded"/>
         <xsd:element name="cascadingChildrenName" type="xsd:string" minOccurs="0"
                      maxOccurs="unbounded"/>
         <xsd:element name="color" type="hudson.model.BallColor" minOccurs="0"/>
         <xsd:element name="firstBuild" type="hudson.model.Run" minOccurs="0"/>
         <xsd:element name="healthReport" type="hudson.model.HealthReport"
                      minOccurs="0" maxOccurs="unbounded"/>
         <xsd:element name="inQueue" type="xsd:boolean"/>
         <xsd:element name="keepDependencies" type="xsd:boolean"/>
         <xsd:element name="lastBuild" type="hudson.model.Run" minOccurs="0"/>
         <xsd:element name="lastCompletedBuild" type="hudson.model.Run"
                      minOccurs="0"/>
         <xsd:element name="lastFailedBuild" type="hudson.model.Run" minOccurs="0"/>
         <xsd:element name="lastStableBuild" type="hudson.model.Run" minOccurs="0"/>
         <xsd:element name="lastSuccessfulBuild" type="hudson.model.Run"
                      minOccurs="0"/>
         <xsd:element name="lastUnstableBuild" type="hudson.model.Run"
                      minOccurs="0"/>
         <xsd:element name="lastUnsuccessfulBuild" type="hudson.model.Run"
                      minOccurs="0"/>
         <xsd:element name="nextBuildNumber" type="xsd:int"/>
         <xsd:element name="property" type="hudson.model.JobProperty" minOccurs="0"
                      maxOccurs="unbounded"/>
         <xsd:element name="queueItem" type="hudson.model.Queue-Item"
                      minOccurs="0"/>
        </xsd:sequence>
       </xsd:extension>
      </xsd:complexContent>
    </xsd:complexType>
    <xsd:complexType name="hudson.model.Queue-Item">
      <xsd:complexContent>
       <xsd:extension base="hudson.model.Actionable">
        <xsd:sequence>
         <xsd:element name="blocked" type="xsd:boolean"/>
         <xsd:element name="buildable" type="xsd:boolean"/>
         <xsd:element name="id" type="xsd:int">
          <xsd:annotation>
           <xsd:documentation>VM-wide unique ID that tracks the {@link Task} as it
                              moves through different stages in the queue (each
                              represented by different subtypes of {@link Item}.</xsd:documentation>
          </xsd:annotation>
         </xsd:element>
         <xsd:element name="inQueueSince" type="xsd:long"/>
         <xsd:element name="params" type="xsd:string" minOccurs="0"/>
         <xsd:element name="stuck" type="xsd:boolean"/>
         <xsd:element name="task" type="xsd:anyType" minOccurs="0">
          <xsd:annotation>
           <xsd:documentation>Project to be built.</xsd:documentation>
          </xsd:annotation>
         </xsd:element>
         <xsd:element name="why" type="xsd:string" minOccurs="0"/>
        </xsd:sequence>
       </xsd:extension>
      </xsd:complexContent>
    </xsd:complexType>
    <xsd:complexType name="hudson.model.Actionable">
      <xsd:sequence>
       <xsd:element name="action" type="xsd:anyType" minOccurs="0"
                    maxOccurs="unbounded"/>
      </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="hudson.model.JobProperty">
      <xsd:sequence/>
    </xsd:complexType>
    <xsd:complexType name="hudson.model.HealthReport">
      <xsd:sequence>
       <xsd:element name="description" type="xsd:string" minOccurs="0"/>
       <xsd:element name="iconUrl" type="xsd:string" minOccurs="0"/>
       <xsd:element name="score" type="xsd:int"/>
      </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="hudson.model.Run">
      <xsd:complexContent>
       <xsd:extension base="hudson.model.Actionable">
        <xsd:sequence>
         <xsd:element name="artifact" type="hudson.model.Run-Artifact" minOccurs="0"
                      maxOccurs="unbounded"/>
         <xsd:element name="building" type="xsd:boolean"/>
         <xsd:element name="description" type="xsd:string" minOccurs="0"/>
         <xsd:element name="duration" type="xsd:long"/>
         <xsd:element name="fullDisplayName" type="xsd:string" minOccurs="0"/>
         <xsd:element name="id" type="xsd:string" minOccurs="0"/>
         <xsd:element name="keepLog" type="xsd:boolean"/>
         <xsd:element name="number" type="xsd:int"/>
         <xsd:element name="result" type="xsd:anyType" minOccurs="0"/>
         <xsd:element name="timestamp" type="xsd:long" minOccurs="0"/>
         <xsd:element name="url" type="xsd:string" minOccurs="0"/>
        </xsd:sequence>
       </xsd:extension>
      </xsd:complexContent>
    </xsd:complexType>
    <xsd:complexType name="hudson.model.Run-Artifact">
      <xsd:sequence>
       <xsd:element name="displayPath" type="xsd:string" minOccurs="0"/>
       <xsd:element name="fileName" type="xsd:string" minOccurs="0"/>
       <xsd:element name="relativePath" type="xsd:string" minOccurs="0">
        <xsd:annotation>
         <xsd:documentation>Relative path name from {@link Run#getArtifactsDir()}</xsd:documentation>
        </xsd:annotation>
       </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="hudson.model.AbstractItem">
      <xsd:complexContent>
       <xsd:extension base="hudson.model.Actionable">
        <xsd:sequence>
         <xsd:element name="description" type="xsd:string" minOccurs="0"/>
         <xsd:element name="displayName" type="xsd:string" minOccurs="0"/>
         <xsd:element name="name" type="xsd:string" minOccurs="0"/>
         <xsd:element name="url" type="xsd:string" minOccurs="0"/>
        </xsd:sequence>
       </xsd:extension>
      </xsd:complexContent>
    </xsd:complexType>
    <xsd:simpleType name="hudson.model.BallColor">
      <xsd:restriction base="xsd:string">
       <xsd:enumeration value="red"/>
       <xsd:enumeration value="red_anime"/>
       <xsd:enumeration value="yellow"/>
       <xsd:enumeration value="yellow_anime"/>
       <xsd:enumeration value="green"/>
       <xsd:enumeration value="green_anime"/>
       <xsd:enumeration value="blue"/>
       <xsd:enumeration value="blue_anime"/>
       <xsd:enumeration value="grey"/>
       <xsd:enumeration value="grey_anime"/>
       <xsd:enumeration value="disabled"/>
       <xsd:enumeration value="disabled_anime"/>
       <xsd:enumeration value="aborted"/>
       <xsd:enumeration value="aborted_anime"/>
      </xsd:restriction>
    </xsd:simpleType>
    </xsd:schema>
    Config.xml
    <?xml version='1.0' encoding='UTF-8'?>
    <project>
      <actions/>
      <description>Sample job ..</description>
      <project-properties class="java.util.concurrent.ConcurrentHashMap">
        <entry>
          <string>hudson-plugins-disk_usage-DiskUsageProperty</string>
          <base-property>
            <originalValue class="hudson.plugins.disk_usage.DiskUsageProperty"/>
            <propertyOverridden>false</propertyOverridden>
          </base-property>
        </entry>
        <entry>
          <string>jdk</string>
          <string-property>
            <originalValue class="string">(Inherit From Job)</originalValue>
            <propertyOverridden>false</propertyOverridden>
          </string-property>
        </entry>
        <entry>
          <string>scm</string>
          <scm-property>
            <originalValue class="hudson.scm.NullSCM"/>
            <propertyOverridden>false</propertyOverridden>
          </scm-property>
        </entry>
      </project-properties>
      <keepDependencies>false</keepDependencies>
      <creationTime>1402648240275</creationTime>
      <properties/>
      <cascadingChildrenNames class="java.util.concurrent.CopyOnWriteArraySet"/>
      <cascading-job-properties class="java.util.concurrent.CopyOnWriteArraySet">
        <string>hudson-plugins-batch_task-BatchTaskProperty</string>
        <string>hudson-plugins-disk_usage-DiskUsageProperty</string>
        <string>hudson-plugins-jira-JiraProjectProperty</string>
        <string>org-hudsonci-plugins-snapshotmonitor-WatchedDependenciesProperty</string>
        <string>hudson-plugins-promoted_builds-JobPropertyImpl</string>
      </cascading-job-properties>
      <scm class="hudson.scm.NullSCM"/>
      <canRoam>false</canRoam>
      <disabled>false</disabled>
      <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
      <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
      <concurrentBuild>false</concurrentBuild>
      <cleanWorkspaceRequired>false</cleanWorkspaceRequired>
    </project>
    the file generated by JAXB are
    com\model\HudsonModelAbstractItem.java
    com\model\HudsonModelAbstractProject.java
    com\model\HudsonModelActionable.java
    com\model\HudsonModelBallColor.java
    com\model\HudsonModelBaseBuildableProject.java
    com\model\HudsonModelFreeStyleProject.java
    com\model\HudsonModelHealthReport.java
    com\model\HudsonModelJob.java
    com\model\HudsonModelJobProperty.java
    com\model\HudsonModelProject.java
    com\model\HudsonModelQueueItem.java
    com\model\HudsonModelRun.java
    com\model\HudsonModelRunArtifact.java
    com\model\HudsonScmRepositoryBrowser.java
    com\model\HudsonScmSCM.java
    com\model\ObjectFactory.java
    Any help will be appreciated .
    Thanks in advance

    Unmarshal the config.xml to Java object.
    Basic JAXB Examples - The Java EE 5 Tutorial

  • XML to java object AND Performance

    Hi,
    I read some article about marshalling a XML file to Java Object (like Castor, XML Beans projects...)
    To resume: I would like to marshal a XML doc (from XML to Java object. Later I would like to put these objects on a SGBD...). Unfortenaly I suppose that approach is to expensive on term of performance? Supposing that my xml doc contain 100 data's occurances, XML bean woulkd create 100 objects corresponding. My problem is that I don't want that the all 100 objects live in the same time on memory. For example, my code will read sequential, the xml occurances (like a Sax parser), create 10 datas objects (standby), put these in the data base, and destroy these objects before...iteratively create the next 10 objects...
    It is possible ? Can anybody help me?
    Thank

    On the article: Java Architecture for XML Binding (JAXB)
    (http://java.sun.com/developer/technicalArticles/WebServices/jaxb/)
    I found maybe a response?
    "...in other words, you can do a SAX parse of a document and then pass the events to JAXB for unmarshalling. "
    But somebody could help me to write the code to do that?

  • How to parse XML for internal table

    hi guys, I would like to know how to parse xml for an internal table. I explain myself.
    Let's say you have a purchase order form where you have header data & items data. In my interactive form, the user can change the purchase order quantity at the item level. When I received back the pdf completed by mail, I need to parse the xml and get the po qty that has been entered.
    This is how I do to get header data from my form
    lr_ixml_node = lr_ixml_document->find_from_name( name = ''EBELN ).
    lv_ebeln = lr_ixml_node->get_value( ).
    How do we do to get the table body??
    Should I used the same method (find_from_name) and passing the depth parameter inside a do/enddo?
    thanks
    Alexandre Giguere

    Alexandre,
    Here is an example. Suppose your internal table is called 'ITEMS'.
    lr_node = lr_document->find_from_name('ITEMS').
    lv_num_of_children = lr_node->num_children( ).
    lr_nodechild = lr_node->get_first_child( ).
    do lv_num_of_children times.
        lv_num_of_attributes = lr_nodechild->num_children( ).
        lr_childchild = lr_nodechild->get_first_child( ).
       do lv_num_of_attributes times.
          lv_value = lr_childchild->get_value( ).
          case sy-index.
             when 1.
               wa_item-field1 = lv_value
             when 2.
               wa_item-field2 = lv_value.
          endcase.
          lr_childchild = lr_childchild->get_next( ).
       enddo.
       append wa_item to lt_item.
       lr_nodechild = lr_nodechild->get_next( ).
    enddo.

Maybe you are looking for