Parse method of JAXP DocumentBuilder using InputStream

I am having some problem. I am working on a generic XML messaging client server pair. The crux of it is that I am using the Transformer object to send data from the client to the server, using a Socket InputStream. The I do exactly the same from the server side to the client side.
Example (client side):
OutputStream out = socket.getOutputStream();
Transformer transformer =
TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(request),
new StreamResult(out));
Example (server side, in the thread for the connection):
InputStream in = socket.getInputStream();
DocumentBuilder builder =
DocumentBuilderFactory.newInstance
().newDocumentBuilder();
Document request = builder.parse(in);
The problem I am experiencing is that the parse method on the server side is never completing. The parse method does not return at all. I can understand that this is due to the InputStream still being open, and need to know how can I let the parse method know that I am done writing to the OutputStream at the client side. Should I be sending an EOF character of sorts? If I should, what byte value represents this, and what do I need to do?
Thank you
Heinrich Pool

Sorry hadn't noticed the Code Tags before. So the code formatted
package de.gaskin.xml;
import de.gaskin.buf.Buffer;
import de.gaskin.io.LineArray;
import de.gaskin.util.Debug;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.Vector;
import org.w3c.dom.Document;
A Simple to use generic XML Document transfer based on sockets.
<H2>Theory of Operation.</h2>
<p>A client sends an array of lines (an XML document) prepended by a line
that ONLY contains an integer (the number of lines in the document that
follows).
<p>The server reads the first line (so that it knows how many lines belong to
the next document) it then reads the specified number of lines into memory and
when all lines have been read in passes them (as an InputStream) to an
XMLParser to produce an XML DOM that is made available through the<br>
<code>getDocument()</code> method.
<h2>API</h2>
The API is very simple to use as the following templates demonstrate.
<h3>Client</h3>
<pre>
    public class MyXmlSocketClient extends XmlSocket {
       MyXmlSocketClient(String serverAddress, String fileName) {
          super(serverAddress, 4711);
          run(fileName);
</pre>
<h3>Server Worker</h3>
    <pre>
    public class MyXmlSocketServer extends XmlSocket {
       MyXmlSocketServer(Socket s) {
          super(s);
       public void run() {
          Document doc = getDocument();
          // Process document
    </pre>
<h3>Server Listener</h3>
    <pre>
    public class MyXmlServer {
       ServerSocket ss;
       boolean      stop;
       MyXmlSocketServer() {
          stop = false;
          try {
             ss = new ServerSocket(4711);
             while (! stop) {
                Socket s = ss.accept();
                new Thread(new MyXmlServerSocket(s));
          catch (Exception x) {
             x.printStackTrace();
    </pre>
<P>Last updated 10th Jan 2001.
@author  David. M. Gaskin.
@version Version 1.0 Oct 2000
@since    Version 1.0
public class XmlSocket implements Runnable {
   final static boolean debug = false;
   protected BufferedReader  data;
  /* protected */ public PrintWriter     pw;
             Socket          socket;
   public XmlSocket(String domain, int port) {
      try {
         socket = new Socket(domain, port);
         common(socket);
      catch (Exception x) {
//       x.printStackTrace();
         throw new Error(x.toString());
   public XmlSocket(Socket s) {
      socket = s;
      common(s);
   void common(Socket s) {
      try {
         data = new BufferedReader(new InputStreamReader(s.getInputStream()));
         pw   = new PrintWriter(s.getOutputStream(), true);
      catch (Exception x) {
//       x.printStackTrace();
         throw new Error(x.toString());
   public Document getDocument() {
      Document rc = null;
      try {
         String line = data.readLine();
         int    linesInDoc = Integer.parseInt(line.trim());
         if (linesInDoc != -1) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            for (int i = 0;i < linesInDoc;i++) {
               line = data.readLine();
               System.out.println(line);
               byte[] byteLine = line.getBytes();
               os.write(byteLine, 0, byteLine.length);
//          System.out.println("END");
            rc = XmlFactory.readIn(new ByteArrayInputStream(os.toByteArray()));
      catch (Exception x) {
         x.printStackTrace();
      return rc;
   public void run(Vector lines) {
      int loopCnt = lines.size();
      if (debug) {
         println("" + loopCnt);
         for (int i = 0;i < loopCnt;i++) {
            println((String)lines.elementAt(i));
//       pw.flush();
         println("-1");
      else {
         pw.println("" + loopCnt);
         for (int i = 0;i < loopCnt;i++) {
            pw.println((String)lines.elementAt(i));
//       pw.flush();
         pw.println("-1");
      pw.flush();
   void println(String s) {
      System.out.println(s);
      pw.println(s);
   public void run() {
      Debug.d(this, "run", "S H O U L D   N E V E R   B E   I N V O K E D");
   public void run(String filename) {
      Buffer[] input = LineArray.readIn(filename);
      send(input);
   public void run(File file) {
      Buffer[] input = LineArray.readIn(file.getAbsolutePath());
      send(input);
   void send(Buffer[] input) {
      int loopCnt = input.length;
      pw.println("" + loopCnt);
      for (int i = 0;i < loopCnt;i++) {
         pw.println(input.toString());
pw.flush();
pw.println("-1");
pw.flush();
public int getDocIdx(String[] roots, Document doc) {
int rc = -1;
String rootName = doc.getDocumentElement().getTagName();
int loopCnt = roots.length;
for (int i = 0;i < loopCnt;i++) {
if (rootName.equals(roots[i])) {
rc = i;
break;
if (rc < 0)
System.out.println(rootName + " N O T F O U N D");
return rc;
public Socket getSocket() {
return socket;
For testing only
public static void main(String[] args) {
XmlSocket xmlS = new XmlSocket("localhost", 36);
xmlS.getDocument();

Similar Messages

  • URGENT:  javax.xml.parsers.DocumentBuilder.parse() method issue

    Hi folks,
    I have an urgent parsing problem. I developed an app with JDK1.4 and now it needs to run on JDK1.3.1. The problem is this:
    If I use the DocumentBuilder.parse() method shipped with JDK1.4 it will parse a document containing namespaces WITHOUT a namespace declaration in the root element. However, since XML support doesn't ship with JDK1.3.1 I need to use JAXP. If I try this with the DocumentBuilder.parse() version shipped with JAXP (latest version) the parse method throws a NullPointerException. If I put the namespace declaration in the document it will parse fine. I tried setting the DocumentBuilderFactory.setNamespaceAware() explicitly to false (should be the default) but no luck. Any ideas other than adding the declaration (long story why I don't want it there...)
    thanks

    example, with declaration of namespace:
    <?xml version="1.0" encoding="UTF-8"?>
    <pre:root xmlns:inn="http://blablabla/inn/version/1.0/">
    <pre:metadata>
    <pre:dublin-core>
    <pre:title>mytitle</pre:title>
    <pre:description>mydesc</pre:description>
    <pre:creator>bjmann</pre:creator>
    </inn:dublin-core>
    </pre:root>
    example, without declaration:
    <?xml version="1.0" encoding="UTF-8"?>
    <pre:root>
    <pre:metadata>
    <pre:dublin-core>
    <pre:title>mytitle</pre:title>
    <pre:description>mydesc</pre:description>
    <pre:creator>bjmann</pre:creator>
    </inn:dublin-core>
    </pre:root>
    this may help...

  • Regarding DocumentBuilder.parse method returns reference as null value.

    Hi
    We are in the process of migrating code which works on WebSphere/JBOSS to WLS..
    We are using DocumentBuilder object for parsing the Locale related xml data. I understand that the DocumentBuilder is provided by DocumentBuilderFactory which is an interface whose implementation is server specific.
    But when the Document Builder parse method is called with a valid file path, we are getting System.Out of doc.getFirstChild().getLocalName() as null (which ideally should have been the name of the first node). No Errors are observed .
    For WLS, the parser is giving the document object reference as null whereas in other servers like Websphere and JBOSS we are able to parse the same xml with proper object reference.
    Could you please help in this regard?
    Thanks and regards
    Anil

    Hi Vmotamar,
    If you think that the parsers available as part of WebLogic are causing the issues, Then you can use your Own Parsers while migrating to WebLogic Server. I mean Get the Parser Jar files which u used as part of JBoss or WebSphere and put it inside the "APP-INF\lib" directory of your EAR Application or Put them inside "WEB-INF\lib" of your WEBApplication...and then Apply ClassLoader Filtering feature provided by WebLogic ...which allows an application to use It's Own Jars\Classes ...
    Please refer to: http://forums.oracle.com/forums/thread.jspa?threadID=1109267&tstart=150 and in http://weblogic-wonders.com/weblogic/parsers_issues
    Thanks
    Jay SenSharma
    http://weblogic-wonders.com/weblogic/parsers_issues/ (WebLogic Wonders Are Here)

  • Using InputStream on EJB method

    Hi everyone,
    i was looking for a way to use InputStream or anything else related to the java.io package on my EJB method. This is the first time that i need to do something like that, so i made a research and i figure out that is impossible use any kind of the io package when i using EJB. Is that true?...
    if this is true, could anyone help me how i can save something on my server using EJB?
    Thanks in Advance

    hi,
    i looked in some forums, and talk with some people who use EJB for so long, and all answers took me to the conclusion that is totally not recommended using streams on ejb methods...i haven't looked on ejb specification to really see if its true...
    Besides, i tried in other way..... first i created my EJB method with a byte[] parameter, and a "service" class which convert this array to an InputStream..and record the file on server...i did a client to test and apparently works without errors, i don't receive any exceptions, so i suppose that at least this part is correct, but i having another problem....
    by the way, anyone know how can i save a certificate on a Keystore??...i'm trying that:
    keyStore = manager.getKeystore("DEFAULT");
         keyStore.load(is, password.toCharArray());     attempting that "is" is the InputStream (same of the problem above) and the second parameter is the password....this code belongs to a method on the "service class" that i mentioned before....
    but nothing happens when i run my app. anyone could help me??
    Thanks in Advance

  • Parse method hangs

    I am trying to to parse a file using DocumentBuilder. The parse() method hangs for no reason. There are no errors or exceptions thrown. I even used a StringReader but in vain. Pl see code below:
    The file is read correctly and i could even print the XML string out.
    System.out.println("Parsing XML file from performParsing():" +s);
              Document doc = null;
              DocumentBuilderFactory factory = null;
              DocumentBuilder builder = null;
              try{
                   factory = DocumentBuilderFactory.newInstance();
                   System.out.println("Parsing XML factory:" +factory);
                   builder = factory.newDocumentBuilder();
                   System.out.println("Parsing XML builder:" +builder);
                   URL url = new URL(s);
                   URLConnection urlConnection = url.openConnection();
                   InputStream in = urlConnection.getInputStream();
                   String XMLStr = getStringReaderFromFile(in); //private method that gives a string
                   StringReader stReader = new StringReader(XMLStr);
                   InputSource ins = new InputSource(stReader);
         doc = builder.parse(ins);--->IT HANGS HERE

    Not an expert on this but presumably you have the properties set up correctly.
    From javadoc ...
    DocumentBuilderFactory uses the system property javax.xml.parsers.XmlDocumentParserFactory to find the class to load. So you can change the parser by calling:
    System.setProperty("javax.xml.parsers.XmlDocumentParserFactory",
    "com.foo.myFactory");

  • Possible to overwrite parse method in DOM with SAX Handler?

    Hi,
    Is it possible to overwrite the parse method within DOM?
    What a want to do is:
         private Node parseXml( String text ) throws SAXParseException, SAXException, IOException, ParserConfigurationException
              SAXParserFactory factory = SAXParserFactory.newInstance();
                   factory.setNamespaceAware(true);
                   SAXParser parser = factory.newSAXParser();
                   TestHandler handler = new TestHandler();
                   // Parse the file
                   parser.parse(new InputSource(new StringReader(text)), handler);
              return (Node)handler.getRoot();
         } //end parseXml()The reason I want to use this is that within SAX I can write my own line counter so I keep a count of which node is on which line of text.
    What I was thinking is that I could use SAX to return DOM Nodes with the line number attached, possibly using the node.setUserData() method?!
    I have tried to play around with it and it doen't seem to work, can anyone help?
    Cheers Alex

    I have managaed to re-write my SAX parser to create a JTree, this works perfectly I can move through the tree and each line of text that corresponds to the node is highlighted.
    My problem is however that in my application I have used the DOM structure throughout so some of the functionality is lost.
    Is I understand that JAXP uses both SAX and DOM together, so I was wondering if it is possible to combine my sax parse method within the DOM?
    If anything is unclear please say and I will try and explain better. The main reason for doing this is that I want to keep a reference to which line of text each node of the dom tree represents. I have not been able to implemnet one in DOM however using SAX I have managed.
    Many thanks,
    Alex

  • Parse method is not possible for this type Exception in web dynpro

    I have a file upload component and one button in a view.
    I have created a binary type context element and mapped it with fileupload component.while clicking the submit button I am getting " Parse method is not possible for this type" exception.
    help me out.

    Hi sridhar,
    Use this code for Upload
    context u create one attribute(up),u assign the data type as "Resource"(which is dictionary type)
    InputStream text = null;
        int temp = 0;
        try
             File file = new File(wdContext.currentContextElement().getUp().getResourceName());
             FileOutputStream op = new FileOutputStream(file);
             if(wdContext.currentContextElement().getUp()!=null)
                  text = wdContext.currentContextElement().getUp().read(false);
                   while((temp=text.read())!=-1)
                                                                       op.write(temp);
             op.flush();
             op.close();
        catch(Exception e)
         e.printStackTrace();   

  • Question About Xerces Parser and Java  JAXP

    Hi,
    I have confusion about both of these API Xerces Parser and Java JAXP ,
    Please tell me both are used for same purpose like parsing xml document and one is by Apache and one is by sun ?
    And both can parse in SAX, or DOM model ?
    Is there any difference in performane if i use xerces in my program rather then JAXP, or is ther any other glance at all.
    Please suggest some thing i have and xml document and i want to parse it.
    Thanks

    Hi
    Xerces is Apaches implementation of W3C Dom specifiacation.
    JAXP is a API for XML parsing its not implementation.
    Sun ships a default implementation for JAXP.
    you have factory methods for selecting a parser at run time or you can set in some config file about what is the implementaion class for the SAXParser is to be chosen (typically you give give the class file of xerces sax parser or dom parser etc..)
    go to IBM Developerworks site and serch for Xerces parser config. which have a good explination of how to do it.
    and browse through j2ee api .may find how to do it.

  • Couldn't parse image from XML file using NSXMLParser

    Hi all, Since i am newbie to developing iPhone application, i have problem in parsing XML data.
    I use the following code for parsing XML file, this is RootViewController.h file
    #import <UIKit/UIKit.h>
    #import "SlideMenuView.h"
    #define kNameValueTag 1
    #define kColorValueTag 2
    #define kSwitchTag 100
    @class DetailViewController;
    @interface RootViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
    DetailViewController *detailViewController;
    UITableView *myTable;
    UIActivityIndicatorView *activityIndicator;
    UIButton *btn;
    CGSize cellSize;
    NSXMLParser *rssParser;
    NSMutableArray *stories;
    NSMutableDictionary *item;
    NSString *currentElement;
    NSMutableString *currentTitle, *currentDate, *currentSummary, *currentLink, *currentImage;
    SlideMenuView *slideMenu;
    NSMutableArray *buttonArray;
    UIButton *rubic;
    UIButton *buurt;
    UIButton *beeld;
    UILabel *lbl;
    NSString *url;
    @property (nonatomic, retain) UITableView *myTable;
    @property (nonatomic, retain) DetailViewController *detailViewController;
    @property (nonatomic, retain) SlideMenuView *slideMenu;
    @property (nonatomic, retain) UIButton *btn;
    @property (nonatomic, retain) NSMutableArray *buttonArray;
    @property (nonatomic, retain) UIButton *rubic;
    @property (nonatomic, retain) UIButton *buurt;
    @property (nonatomic, retain) UIButton *beeld;
    @property (nonatomic, retain) UILabel *lbl;
    @end
    below is the RootViewController.m file,
    #import <Foundation/Foundation.h>
    #import "RootViewController.h"
    #import "DetailViewController.h"
    #import "SlideMenuView.h"
    @implementation RootViewController
    @synthesize rubic, buurt, beeld, detailViewController, myTable, btn, buttonArray, slideMenu, lbl;
    - (void)parseXMLFileAtURL:(NSString *)URL {
    stories = [[NSMutableArray alloc] init];
    //you must then convert the path to a proper NSURL or it won't work
    NSURL *xmlURL = [NSURL URLWithString:URL];
    // here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
    // this may be necessary only for the toolchain
    rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [rssParser setDelegate:self];
    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [rssParser setShouldProcessNamespaces:NO];
    [rssParser setShouldReportNamespacePrefixes:NO];
    [rssParser setShouldResolveExternalEntities:NO];
    [rssParser parse];
    - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]];
    NSLog(@"error parsing XML: %@", errorString);
    UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    //NSLog(@"found this element: %@", elementName);
    currentElement = [elementName copy];
    if ([elementName isEqualToString:@"item"]) {
    // clear out our story item caches...
    item = [[NSMutableDictionary alloc] init];
    currentTitle = [[NSMutableString alloc] init];
    currentDate = [[NSMutableString alloc] init];
    currentSummary = [[NSMutableString alloc] init];
    currentLink = [[NSMutableString alloc] init];
    currentImage = [[NSMutableString alloc] init];
    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    //NSLog(@"ended element: %@", elementName);
    if ([elementName isEqualToString:@"item"]) {
    // save values to an item, then store that item into the array...
    [item setObject:currentTitle forKey:@"title"];
    [item setObject:currentSummary forKey:@"summary"];
    [item setObject:currentDate forKey:@"date"];
    [item setObject:currentImage forKey:@"enclosure"];
    [stories addObject:[item copy]];
    NSLog(@"adding story: %@", currentTitle);
    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    //NSLog(@"found characters: %@", string);
    // save the characters for the current item...
    if ([currentElement isEqualToString:@"title"]) {
    [currentTitle appendString:string];
    } else if ([currentElement isEqualToString:@"description"]) {
    [currentSummary appendString:string];
    } else if ([currentElement isEqualToString:@"pubDate"]) {
    [currentDate appendString:string];
    } else if ([currentElement isEqualToString:@"enclosure"]) {
    [currentImage appendString:string];
    - (void)parserDidEndDocument:(NSXMLParser *)parser {
    [activityIndicator stopAnimating];
    [activityIndicator removeFromSuperview];
    NSLog(@"all done!");
    NSLog(@"stories array has %d items", [stories count]);
    [myTable reloadData];
    - (void)loadView {
    //self.title = @"GVA_iPhone";
    //UIImage *img = [UIImage imageNamed: @"gva_v2.1.png"];
    CGRect frame = [[UIScreen mainScreen] bounds];
    UIView *aView = [[UIView alloc] initWithFrame:frame];
    aView.backgroundColor = [UIColor grayColor];
    self.view = aView;
    [aView release];
    lbl = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 33.0, 320.0, 30.0)];
    lbl.backgroundColor = [UIColor colorWithRed:21.0/255.0 green:113.0/255.0 blue:194.0/255.0 alpha:1.0];
    lbl.textColor = [UIColor whiteColor];
    lbl.font = [UIFont boldSystemFontOfSize:18.0];
    [self.view addSubview:lbl];
    [lbl release];
    buttonArray = [[NSMutableArray alloc] init];
    for(int i = 1; i < 4; i++)
    // Rounded rect is nice
    //UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    // Give the buttons a width of 100 and a height of 30. The slide menu will take care of positioning the buttons.
    // If you don't know that 100 will be enough, use my function to calculate the length of a string. You find it on my blog.
    [btn setFrame:CGRectMake(0.0f,3.0f, 120.0f, 30.0f)];
    switch(i){
    case 1:
    [btn setTitle:[NSString stringWithFormat:@" Snel", i+1] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"topbg02.png"] forState:UIControlStateNormal];
    lbl.text = @" Snel";
    [btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [buttonArray addObject:btn];
    break;
    case 2:
    [btn setTitle:[NSString stringWithFormat:@" Binnenland", i+1] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"topbg02.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [buttonArray addObject:btn];
    break;
    case 3:
    [btn setTitle:[NSString stringWithFormat:@" Buitenland", i+1] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"topbg02.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
    [buttonArray addObject:btn];
    break;
    [btn release];
    slideMenu = [[SlideMenuView alloc]initWithFrameColorAndButtons:CGRectMake(0.0, 3.0, 330.0, 30.0) backgroundColor:[UIColor blackColor] buttons:buttonArray];
    [self.view addSubview:slideMenu];
    UITableView *aTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 63.0, 320.0, 310.0)];
    aTableView.dataSource = self;
    aTableView.delegate = self;
    aTableView.rowHeight = 120;
    self.myTable = aTableView;
    [aTableView release];
    [self.view addSubview:myTable];
    rubic = [[UIButton alloc]initWithFrame:CGRectMake(0.0, 370.0, 105.0, 50.0)];
    [rubic setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rubic setBackgroundImage:[UIImage imageNamed:@"MOUSEOVER.png"] forState:UIControlStateNormal];
    [rubic addTarget:self action:@selector(buttonBinn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rubic];
    UILabel *lblRub = [[UILabel alloc]initWithFrame:CGRectMake(10.0, 385.0, 45.0, 12.0)];
    lblRub.text = @"Rubriek";
    lblRub.font = [UIFont boldSystemFontOfSize:11.0];
    lblRub.backgroundColor = [UIColor clearColor];
    lblRub.textColor = [UIColor whiteColor];
    [self.view addSubview:lblRub];
    UIImageView *imgCat = [[UIImageView alloc] initWithFrame:CGRectMake(58.0, 375.0, 39.0, 36.0)];
    imgCat.image = [UIImage imageNamed:@"category_icon.png"];
    [self.view addSubview:imgCat];
    buurt = [[UIButton alloc] initWithFrame:CGRectMake(105.0, 370.0, 108.0, 50.0)];
    [buurt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buurt setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [buurt addTarget:self action:@selector(buttonBuurt:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buurt];
    UILabel *lblGlo = [[UILabel alloc]initWithFrame:CGRectMake(112.0, 385.0, 59.0, 12.0)];
    lblGlo.text = @"In de Buurt";
    lblGlo.font = [UIFont boldSystemFontOfSize:11.0];
    lblGlo.backgroundColor = [UIColor clearColor];
    lblGlo.textColor = [UIColor whiteColor];
    [self.view addSubview:lblGlo];
    UIImageView *imgGlo = [[UIImageView alloc] initWithFrame:CGRectMake(173.0, 375.0, 39.0, 36.0)];
    imgGlo.image = [UIImage imageNamed:@"globe_icon.png"];
    [self.view addSubview:imgGlo];
    beeld = [[UIButton alloc]initWithFrame:CGRectMake(213.0, 370.0, 108.0, 50.0)];
    [beeld setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [beeld setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [beeld addTarget:self action:@selector(buttonBeeld:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:beeld];
    UILabel *lblCam = [[UILabel alloc]initWithFrame:CGRectMake(228.0, 385.0, 45.0, 12.0)];
    lblCam.text = @"In Beeld";
    lblCam.font = [UIFont boldSystemFontOfSize:11.0];
    lblCam.backgroundColor = [UIColor clearColor];
    lblCam.textColor = [UIColor whiteColor];
    [self.view addSubview:lblCam];
    UIImageView *imgCam = [[UIImageView alloc] initWithFrame:CGRectMake(276.0, 375.0, 39.0, 36.0)];
    imgCam.image = [UIImage imageNamed:@"camera_icon.png"];
    [self.view addSubview:imgCam];
    if([stories count] == 0) {
    [self parseXMLFileAtURL:@"http://iphone.concentra.exuvis.com/feed/rss/article/2/binnenland.xml"];
    cellSize = CGSizeMake([myTable bounds].size.width,60);
    - (IBAction)buttonPressed:(id)sender {
    lbl.text = ((UIButton*)sender).currentTitle;
    - (IBAction)buttonClicked:(id)sender {
    lbl.text = ((UIButton*)sender).currentTitle;
    - (IBAction)buttonTouched:(id)sender {
    lbl.text = ((UIButton*)sender).currentTitle;
    -(void)buttonBinn:(id)sender
    [rubic setBackgroundImage:[UIImage imageNamed:@"MOUSEOVER.png"] forState:UIControlStateNormal];
    [buurt setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [beeld setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    -(void)buttonBuurt:(id)sender
    [buurt setBackgroundImage:[UIImage imageNamed:@"MOUSEOVER.png"] forState:UIControlStateNormal];
    [beeld setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [rubic setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    -(void)buttonBeeld:(id)sender
    [beeld setBackgroundImage:[UIImage imageNamed:@"MOUSEOVER.png"] forState:UIControlStateNormal];
    [rubic setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    [buurt setBackgroundImage:[UIImage imageNamed:@"bottombg01.png"] forState:UIControlStateNormal];
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    - (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
    - (void)dealloc {
    [myTable release];
    [detailViewController release];
    [super dealloc];
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [stories count];
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GVAiPhone"];
    if (cell == nil) {
    //CGRect cellFrame = CGRectMake(0, 0, 300, 65);
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"GVAiPhone"] autorelease];
    //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    //cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow_icon.png"]];
    CGRect nameValueRect = CGRectMake(5, 5, 275, 35);
    UILabel *nameValue = [[UILabel alloc] initWithFrame:nameValueRect];
    nameValue.tag = kNameValueTag;
    nameValue.font = [UIFont fontWithName:@"Arial" size:15.0];
    nameValue.lineBreakMode = UILineBreakModeWordWrap;
    nameValue.numberOfLines = 2;
    [cell.contentView addSubview:nameValue];
    [nameValue release];
    CGRect colorValueRect = CGRectMake(5, 38, 275, 65);
    UILabel *colorValue = [[UILabel alloc] initWithFrame:colorValueRect];
    colorValue.tag = kColorValueTag;
    colorValue.font = [UIFont fontWithName:@"Arial" size:11.0];
    colorValue.textColor = [UIColor colorWithRed:130.0/255.0 green:135.0/255.0 blue:139.0/255.0 alpha:1.0];
    colorValue.lineBreakMode = UILineBreakModeWordWrap;
    colorValue.textAlignment = UITextAlignmentLeft;
    colorValue.numberOfLines = 6;
    [cell.contentView addSubview:colorValue];
    [colorValue release];
    // Set up the cell
    //cell.text = [theSimpsons objectAtIndex:indexPath.row];
    //cell.hidesAccessoryWhenEditing = YES;
    NSUInteger storyIndex = [indexPath row];
    NSDictionary *rowData = [stories objectAtIndex:storyIndex];
    UILabel *name = (UILabel *)[cell.contentView viewWithTag:kNameValueTag];
    name.text = [rowData objectForKey:@"title"];
    //name.lineBreakMode;
    //UIImage *image =[UIImage imageNamed: currentImage];imageWithContentsOfFile
    //image.size.width = 50;
    //iimage.size.height = 50;
    //cell.image = [UIImage imageNamed:currentImage];
    cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow_icon.png"]];
    UILabel *color = (UILabel *)[cell.contentView viewWithTag:kColorValueTag];
    color.text = [rowData objectForKey:@"summary"];
    return cell;
    @end
    - here the actual problem is the xml node <enclosure> contains images but in using the method "didEndElement" , it doesn't parse into the <enclosure> node. ya so please help me in parsing and getting the image.
    Waiting for your help !!
    -Sathiya

    Hi, how did you solve your problem in detail. I'm having the same problem with this rss-feed: www.spiegel.de/index.rss
    I cannot parse the url of the images. I'm looking forward to your answer.

  • Syntax Error with JSON.Parse method to parse SharePoint List Items

    Hi All,
    I want to get SharePoint List data and bind that retrived data to the JQuery Grid Control.
    For this I used SPServices to get the SharePoint List data in SOAP Envelope. Now I need to parse the soap envelope and store the retrieved items in array to pass it to the Grid Control.
    While using the JSON.Parse(resporseText) method, Iam consistenly getting an Syntax Error!
    Could anyone help me with this ?
    Please find the SOAP Envelope I received from SP List as below:
    "<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/"><GetListItemsResult><listitems xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882'
    xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
    xmlns:rs='urn:schemas-microsoft-com:rowset'
    xmlns:z='#RowsetSchema'>
    <rs:data ItemCount="2">
    <z:row ows_OBNumber='112211.000000000' ows_Project_x0020_Name='Project 1' ows_MetaInfo='11;#' ows__ModerationStatus='0' ows__Level='1' ows_Title='Project 1' ows_ID='11' ows_UniqueId='11;#{FBBCBCF9-666D-42F9-92D7-67188C51BC9B}' ows_owshiddenversion='1' ows_FSObjType='11;#0' ows_Created='2015-01-12 10:25:06' ows_PermMask='0x7fffffffffffffff' ows_Modified='2015-01-12 10:25:06' ows_FileRef='11;#sites/Lists/Projects/11_.000' />
    <z:row ows_OBNumber='1122343.00000000' ows_Project_x0020_Name='Project 2 ' ows_MetaInfo='12;#' ows__ModerationStatus='0' ows__Level='1' ows_Title='Project 2' ows_ID='12' ows_UniqueId='12;#{0D772B76-68E4-4769-B6FF-6A269F9C7ABD}' ows_owshiddenversion='1' ows_FSObjType='12;#0' ows_Created='2015-01-12 10:33:48' ows_PermMask='0x7fffffffffffffff' ows_Modified='2015-01-12 10:33:48' ows_FileRef='12;#sites/Lists/Projects/12_.000' />
    </rs:data>
    </listitems></GetListItemsResult></GetListItemsResponse></soap:Body></soap:Envelope>"
    Any help on this will be greatly appreciated.
    Thanks In Advance.!

    Hi,
    According to your description, there is an issue when parsing result from the data retrieved using SPServices.
    By default, SPServices returns data as XML format, however, the JSON.parse() method “Throws a SyntaxError exception if the string to parse is not valid JSON”:
    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
    To extract the data needed from the response, you can either take the demo below for as a reference:
    http://spservices.codeplex.com/wikipage?title=GetListItems
    Or use the jQuery.parseXML() function:
    http://api.jquery.com/jquery.parsexml/
    Best regards
    Patrick Liang
    TechNet Community Support

  • Failed to parse method name:

    Hi,
    I've the following environment:
    - Sun Solaris
    - WL 61 without service pack
    - jdk 1.3.1
    I wrote a simple Session Bean and make it IIOP enabled.
    For the Java-Corba client I use an IDL which describes
    the interfaces of the remote and home interface of the
    Session Bean.
    Everything works fine, that means I get the WL's NameService,
    home and the remote object. If I call a method of the remote
    object I got the following message:
    <Info> <IIOPEndPoint> <failed to parse method name: foundUnkownSubscriber>
    I found something in you newsgroup and you said the we should
    use SP2. Where can I get this SP2?
    Regards
    Andre Genser

    Andy Piper <[email protected]> wrote:
    "Andre Genser" <[email protected]> writes:
    I've the following environment:
    - Sun Solaris
    - WL 61 without service pack
    - jdk 1.3.1
    I wrote a simple Session Bean and make it IIOP enabled.
    For the Java-Corba client I use an IDL which describes
    the interfaces of the remote and home interface of the
    Session Bean.
    Everything works fine, that means I get the WL's NameService,
    home and the remote object. If I call a method of the remote
    object I got the following message:
    <Info> <IIOPEndPoint> <failed to parse method name: foundUnkownSubscriber>Are you sure you are spelling correctly? Seems like this should be
    foundUnknownSubscriber.
    andy
    -- Sorry Andy, it was the name but I didn't solved the problem. Now I got the following
    exception:
    <Apr 16, 2002 8:47:29 AM CEST> <Warning> <Dispatcher> <Error thrown by rmi server:
    'weblogic.rmi.cluster.ClusterableServerRef@111 - jvmid: '-5101001595216439928S:10.2.9.70:[8045,8045,9045,9045,8045,9045,-1]:agenser8045:myserver',
    oid: '273', implementation: '[BaseEJBObject] home: prototype.CallBackBean_w4a7u3_HomeImpl@29bced''
    java.lang.OutOfMemoryError
    <<no stack trace available>>
    >
    <Apr 16, 2002 8:47:29 AM CEST> <Error> <Kernel> <ExecuteRequest failed
    java.lang.OutOfMemoryError
    <<no stack trace available>>
    >
    What is wrong in my solution? Here is my simple IDL-File:
    module prototype{
         exception CallBackException {
         interface CallBack {
              void foundUnknownSubscriber( in string MSISDN) raises(CallBackException);
         interface CallBackFactory {
              CallBack create();
    Thanks.
    Andre

  • HTMLEditorKit.Parser.parse() method is not giving a proper HTMLDocument alw

    Hi,
    I am developing util program for HTML filter, for my project. I have find using HTMLDocument we can do that.
    But when I created I found few starnge things.
    HTMLEditorKit.Parser.parse() method is not giving a proper HTMLDocument always. the below application will show the HTML one if you comment the String str ="" ; and uncomment the next line.
    I am wondering why this happens.
    import java.io.StringReader;
    import java.io.StringWriter;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.html.HTMLEditorKit;
    import javax.swing.text.html.HTMLWriter;
    import javax.swing.text.html.parser.ParserDelegator;
    public class HTMLDocExample {
    public static void main(String args[]) throws Exception {
    System.out.println("start the parsing");
    String data = "dsfdssfsdf<A HREF='http://yahoo.com'>HTMLEditorKit.Parser</A><h1>dsfdsf</h1><table border='1' class='test'><tr><td><input type='text'>dfsf</input><select id='id1' name='name1'><option>fff</option><option>aaaaa</option></select><input type='text'/><a href=#></a></td></tr></table>";
    String str ="" ;
    //String str ="<TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE>" ;
    StringReader br = new StringReader(data + str );
    HTMLEditorKit htmlKit = new HTMLEditorKit();
    HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
    parser.parse(br, callback, true);
    StringWriter writer = new StringWriter();
    HTMLWriter hWriter = new HTMLWriter(writer, htmlDoc);
    hWriter.write();
    String outPut = writer.toString();
    System.out.println(outPut);
    System.exit(0);
    }

    import java.io.StringReader;
    import java.io.StringWriter;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.html.HTMLEditorKit;
    import javax.swing.text.html.HTMLWriter;
    import javax.swing.text.html.parser.ParserDelegator;
    public class HTMLDocExample {
      public static void main(String args[]) throws Exception {
        System.out.println("start the parsing"); 
        String data = "dsfdssfsdf<A HREF='http://yahoo.com'>HTMLEditorKit.Parser</A><h1>dsfdsf</h1><table border='1' class='test'><tr><td><input type='text'>dfsf</input><select id='id1' name='name1'><option>fff</option><option>aaaaa</option></select><input type='text'/><a href=#></a></td></tr></table>";
        //String str ="" ;
        String str ="<TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE><TABLE >test</TABLE>" ;
        StringReader br = new StringReader(data + str );   
        HTMLEditorKit htmlKit = new HTMLEditorKit();
        HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
        HTMLEditorKit.Parser parser = new ParserDelegator();
        HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
        parser.parse(br, callback, true);
        StringWriter writer = new StringWriter();
        HTMLWriter hWriter = new HTMLWriter(writer, htmlDoc);
        hWriter.write();
        String outPut = writer.toString();       
        System.out.println(outPut);
        System.exit(0);
    }

  • DateFormat parse method usage

    Hi all,
    I am using the following code to parse the date String object to Date Object -
    ======================================================================
    if(dateString == null || dateString.trim().equals(""))
    return null;
    DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.SHORT,
    Locale.getDefault());
    Date d = null;
    try
    dateFormatter.setLenient(false);
    d = dateFormatter.parse(dateString);
    catch(ParseException pe)
    e.printStackTrace();
    =================================================================
    This code works perfectly for all formats of String objects I give except for the format - "12/12/12/1" in which case it converts to following date object -
    "Wed Dec 12 00:00:00 IST 2012" although its an invalid date String.
    Please let me know how I could have correct validation done in such cases or if this is the right behavior for DateFormat class.
    Thanks in advance!!

    I'm not going to comment on how exactly the parse method does its business, but I can suggest you use a regex pattern to validate the input you will send the parse method.
    Here is some info from the CodeProject website on date validation(Note that this is aimed at .NET - but regex works the same in Java as it does in .NET [i think]):
    Dates: As with numbers, we need two validators: a key-press validator, and a completion validator. The key-press validator can be pretty simple, if we limit how our user enters the date. Let’s say that we want to validate for the U.S. date format mm/dd/yyyy. Here is a validator that will do that:
    ^([0-9]|/)*$
    The regex reads: “Match any string that contains a sequence of zero or more characters, where each character is either a digit or a slash.” This validator will give the user immediate feedback if they enter an invalid character, such as an ‘a’.
    Copy that regex to Regex Tester and give it a try. Note that the validation fails if the user enters dashes, instead of slashes, between the parts of the date. How could we increase the flexibility of our regex to accommodate dashes? Think about the question for a minute before moving on.
    All we need to do is add a dash to the alternates group:
    ^([0-9]|/|-)*$
    We could add other alternates to make the regex as flexible as it needs to be.
    The completion validator does a final check to determine whether the input matches a complete date pattern:
    ^[0-2]?[1-9](/|-)[0-3]?[0-9](/|-)[1-2][0-9][0-9][0-9]$
    The regex reads as follows: "Match any string that conforms to this pattern: The first character can be a 0, 1, or 2, and it may be omitted. The second character can be any number and is required. The next character can be a slash or a dash, and is required…” And so on. This regex differs from the ones we used before in that it specifies each character of the pattern—the pattern is more of a template than a formula.
    Note the first character of the regex: ‘[0-2]’. This character points out that we can limit allowable digits to less than the full set. We can also expand them; for example, ‘[0-9A-F]’ would allow any hexadecimal digit. In fact, we can use this structure, known as a character class, to specify any set of characters we want. For example, the character class ‘[A-Z]’ allows capital letters, and ‘[A-Za-z]’ allows upper or lower-case letters.
    Our date regex also points out some of the limitations of regex validation. Paste the date regex shown into Regex Tester and try out some dates. The regex does a pretty good job with run-of-the-mill dates, but it allows some patently invalid ones, such as ‘29/29/2006’, or ‘12/39/2006'. The regex is clearly not ‘bulletproof’.
    We could beef up the regular expression with additional features to catch these invalid dates, but it may be simpler to simply use a bit of .NET in the completion validator:
    bool isValid = DateTime.TryParse(dateString, out dummy);
    We gain the additional benefit that .NET will check the date for leap year validity, and so on. As always, the choice comes down to: What is simpler? What is faster? What is more easily understood? In my shop, we use a regex for the key-press validator, and DateTime.TryParse() for the completion validator.
    Oh - and there is another regex validator:
    ^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$
    which matches the yyyy-mm-dd date format and also validates month and number of days in a month. Could be improved as currently all leap year dates (yyyy-02-29) will validate.
    Sorry if I couldn't be of more help...
    Edited by: JoKiLlSyA on Oct 9, 2008 11:22 PM

  • Error msg Parse Methode ist fu00FCr diesen Typ nicht mu00F6glich

    Hi
    I have an app which loads an interactive form the user fills out on his desktop. When loading this form I get an error msg inside my browser that reads:
    Parse Methode ist für diesen Typ nicht möglich
    or in English:
    Impossible to use parse method for this type
    Any idea why this happens?
    An urgent reply would be highly appreciated.
    regards
    yuval peery

    Michael hi
    Tks for yr early reply.
    I pasted the snippet you supplied into my FormView.wdDoInit().
    Same effect. No help!
    I almost know for sure that during object instantiation FormView should load the object put in pdfSource and then display it. I am not so sure  how this is done.
    Any further insight would be highly appreciated
    mfG
    Yuval

  • How to validate XML against XSD and parse/save in one step using SAXParser?

    How to validate XML against XSD and parse/save in one step using SAXParser?
    I currently have an XML file and XSD. The XML file specifies the location of the XSD. In Java code I create a SAXParser with parameters indicating that it needs to validate the XML. However, SAXParser.parse does not validate the XML, but it does call my handler functions which save the elements/attributes in memory as it is read. On the other hand, XMLReader.parse does validate the XML against the XSD, but does not save the document in memory.
    My code can call XMLReader.parse to validate the XML followed by SAXParser.parse to save the XML document in memory. But this sound inefficient. Besides, while a valid document is being parsed by XMLReader, it can be changed to be invalid and saved, and XMLReader.parse would be looking at the original file and would think that the file is OK, and then SAXParser.parse would parse the document without errors.
    <Book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="book.xsd" name="MyBook">
      <Chapter name="First Chapter"/>
      <Chapter name="Second Chapter">
        <Section number="1"/>
        <Section number="2"/>
      </Chapter>
    </Book>
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="Book">
    <xs:complexType>
      <xs:sequence>
       <xs:element name="Chapter" minOccurs="0" maxOccurs="unbounded">
        <xs:complexType>
         <xs:sequence>
          <xs:element name="Section" minOccurs="0" maxOccurs="unbounded">
           <xs:complexType>
            <xs:attribute name="xnumber"/>
          </xs:complexType>
          </xs:element>
         </xs:sequence>
         <xs:attribute name="name"/>
        </xs:complexType>
       </xs:element>
      </xs:sequence>
      <xs:attribute name="name"/>
    </xs:complexType>
    </xs:element>
    </xs:schema>
    public class SAXXMLParserTest
       public static void main(String[] args)
          try
             SAXParserFactory factory = SAXParserFactory.newInstance();
             factory.setNamespaceAware(true);
             factory.setValidating(true);
             SAXParser parser = factory.newSAXParser();
             parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                                "http://www.w3.org/2001/XMLSchema");
             BookHandler handler = new BookHandler();
             XMLReader reader = parser.getXMLReader();
             reader.setErrorHandler(handler);
             parser.parse("xmltest.dat", handler); // does not throw validation error
             Book book = handler.getBook();
             System.out.println(book);
             reader.parse("xmltest.dat"); // throws validation error because of 'xnumber' in the XSD
    public class Book extends Element
       private String name;
       private List<Chapter> chapters = new ArrayList<Chapter>();
       public Book(String name)
          this.name = name;
       public void addChapter(Chapter chapter)
          chapters.add(chapter);
       public String toString()
          StringBuilder builder = new StringBuilder();
          builder.append("<Book name=\"").append(name).append("\">\n");
          for (Chapter chapter: chapters)
             builder.append(chapter.toString());
          builder.append("</Book>\n");
          return builder.toString();
       public static class BookHandler extends DefaultHandler
          private Stack<Element> root = null;
          private Book book = null;
          public void startDocument()
             root = new Stack<Element>();
          public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
             if (qName.equals("Book"))
                String name = attributes.getValue("name");
                root.push(new Book(name));
             else if (qName.equals("Chapter"))
                String name = attributes.getValue("name");
                Chapter child = new Chapter(name);
                ((Book)root.peek()).addChapter(child);
                root.push(child);
             else if (qName.equals("Section"))
                Integer number = Integer.parseInt(attributes.getValue("number"));
                Section child = new Section(number);
                ((Chapter)root.peek()).addSection(child);
                root.push(child);
          public void endElement(String uri, String localName, String qName) throws SAXException
             Element finished = root.pop();
             if (root.size() == 0)
                book = (Book) finished;
          public Book getBook()
             return book;
          public void error(SAXParseException e)
             System.out.println(e.getMessage());
          public void fatalError(SAXParseException e)
             error(e);
          public void warning(SAXParseException e)
             error(e);
    public class Chapter extends Element
       public static class Section extends Element
          private Integer number;
          public Section(Integer number)
             this.number = number;
          public String toString()
             StringBuilder builder = new StringBuilder();
             builder.append("<Section number=\"").append(number).append("\"/>\n");
             return builder.toString();
       private String name;
       private List<Section> sections = null;
       public Chapter(String name)
          this.name = name;
       public void addSection(Section section)
          if (sections == null)
             sections = new ArrayList<Section>();
          sections.add(section);
       public String toString()
          StringBuilder builder = new StringBuilder();
          builder.append("<Chapter name=\"").append(name).append("\">\n");
          if (sections != null)
             for (Section section: sections)
                builder.append(section.toString());
          builder.append("</Chapter>\n");
          return builder.toString();
    }Edited by: sn72 on Oct 28, 2008 1:16 PM

    Have you looked at the XML DB FAQ thread (second post) in this forum? It has some examples for validating XML against schemas.

Maybe you are looking for

  • Multiple logon pages according to aliaas

    hello all, I need to display different logon pages according to the url used to access the portal. can anyone please help me. I have tried portal aliases but this does not give the wanted effect. it is driving me crazy. thanks a lot for your time, ol

  • How do I reinstall "Printed Documentation"?

    When I try to print documentation in RoboHelp HTML 6, I get the message "The Word VBA macro version registered is incorrect. Please reinstall Printed Documentation." I've tried uninstalling and reinstalling RoboHelp, and that doesn't fix the problem.

  • Does anyone have a PowerShell script which change the paper source on a Canon Image Runner Advance?

    I came across this Powershell script on the web, which does a good job of printing out PDFs: Start-Process -FilePath "C:\Users\Test\Documents\Listing.pdf" –Verb Print -PassThru | %{sleep 10;$_} | kill Start-Process -FilePath "C:\Users\Test\Documents\

  • Limited codecs choices in QT Pro and other applications

    On my home computer when I access QT Player and use the export option and export as a QT movie, I have a long list of encoders to choose from in the drop down selection list.  Apple ProRes 422 is among them. On my work computer when I try to select a

  • Won't allow me to access my project.

    I'm editing my media project on the latest version of iMovie, and everything started going wrong. First it shut down on me with no warning, but when i accessed it again it worked fine for a while. Then it started saying that the source clips weren't