Parse of a xml file to an java object model

Hello,
I'm trying to do a program that receive an xml file and ought to create all the neccesary java objects according to the content of the parsed xml file.
I've all the class created for all the objects that could be present into the xml and the idea is to go down in the tree of nodes recursively until it returns nodes more simple. Then, I create the last object and while I come back of the recursively calls, I create the objects more complex until I reached to the main object.
Until now, I have part of this code, that is the one wich have to parse the parts of the xml.
public static void readFile(String root){
          DocumentBuilderFactory factory = DocumentBuilderFactory
               .newInstance();
          try {
               DocumentBuilder builder = factory.newDocumentBuilder();
               Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
               String contents = scanner.next();
               scanner.close();
               Document document = builder.parse(new ByteArrayInputStream(contents.getBytes()));
               Node node = null;
               NodeList nodes = null;
               Element element = document.getDocumentElement();
               System.out.println(element.getNodeName());
               NodeList subNodes;
               NamedNodeMap attributes;
               //if (element.hasAttributes())
               visitNodes(element);
          } catch (ParserConfigurationException e) {
               e.printStackTrace();
          } catch (SAXException e) {
               e.printStackTrace();
          } catch (IOException e) {
               e.printStackTrace();
     private static void visitNodes (Node node){
          for(Node childNode = node.getFirstChild(); childNode!=null;){
               if (childNode.getNodeType() == childNode.DOCUMENT_NODE){
                    System.out.println("Document node Name " + childNode.getNodeName());
                    visitNodes(childNode);
               }else if (childNode.getNodeType() == childNode.ELEMENT_NODE){
                    System.out.println("Node Name " + childNode.getNodeName());
                    if (childNode.hasAttributes()){
                         visitAttributes(childNode.getAttributes());
                    if (childNode.hasChildNodes()){
                         visitNodes(childNode);
               }else if (childNode.getNodeType() == childNode.TEXT_NODE && !childNode.getNodeValue().contains("\n\t")){
                    System.out.println("Node value " + childNode.getNodeValue());
               Node nextChild = childNode.getNextSibling();
               childNode = nextChild;
     private static void visitAttributes(NamedNodeMap attributes){
          Node node;
          for(int i = 0; i < attributes.getLength(); i++){
               node = attributes.item(i);
               System.out.print(node.getNodeName() + " ");
               System.out.print(node.getNodeValue() + " ");
              }I don't know the use of childNodeType. For example, I expected that the XML tags with childs in his structure, enter by the option NODE_DOCUMENT and the tags without childs by the ELEMENT_NODE.
But the most important problem I've found are the nodes [#text] because after one ELEMENT_NODE I always found this node and when I ask if the node hasChilds, always returns true by this node.
Has any option to obtain this text value, that finally I want to display without doing other recursively call when I enter into the ELEMENT_NODE option?
When one Node is of type DOCUMENT_NODE or DOCUMENT_COMMENT? My program always enter by the ELEMENT_NODE type
Have you any other suggestions? All the help or idea will be well received.
Thanks for all.

Hello again,
My native language is Spanish and sorry by my English I attemp write as better I can, using my own knowledge and the google traductor.
I have solved my initial problem with the xml parser.
Firstly, I read the complete XML file, validated previously.
The code I've used is this:
public static String readCompleteFile (String root){
          String content = "";
          try {
               Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
               content = scanner.next();
               scanner.close();
          } catch (IOException e) {
               e.printStackTrace();
          return content;
     }Now, I've the file in memory and I hope I can explain me better.
I can receive different types of XML that could be or not partly equals.
For this purpose I've created an external jar library with all the possible objects contained in my xml files.
Each one of this objects depend on other, until found leaf nodes.
For example, If I receive one xml with a scheme like the next:
<Person>
    <Name>Juliet</Name>
    <Father Age="30r">Peter</Father>
    <Mother age="29">Theresa</Mother>
    <Brother>
    </Brother>
    <Education>
        <School>
        </school>
    </education>
</person>
<person>
</person>The first class, which initializes the parse, should selecting all the person tags into the file and treat them one by one. This means that for each person tag found, I must to call each subobject wich appears in the tag. using as parameter his own part of the tag and so on until you reach a node that has no more than values and or attributes. When the last node is completed I'm going to go back for completing the parent objects until I return to the original object. Then I'll have all the XML in java objects.
The method that I must implement as constructor in every object is similar to this:
public class Person{
  final String[] SUBOBJETOS = {"Father", "Mother", "Brothers", "Education"};
  private String name;
     private Father father;
     private Mother mother;
     private ArrayList brothers;
     private Education education;
     public Person(String xml){
       XmlUtil utilXml = new XmlUtil();          
          String xmlFather = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[0]);
          String xmlMother = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[1]);
          String xmlBrothers = utilXml.textBetweenMultipleXmlTags(xml, SUBOBJETOS[2]);
          String xmlEducation = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[3]);
          if (!xmlFather.equals("")){
               this.setFather(new Father(xmlFather));
          if (!xmlMother.equals("")){
               this.setMother(new Father(xmlMother));
          if (!xmlBrothers.equals("")){
            ArrayList aux = new ArrayList();
            String xmlBrother;
            while xmlBrothers != null && !xmlBrothers.equals("")){
              xmlBrother = utilXml.textBetweenXmlTags(xmlBrothers, SUBOBJETOS[2]);
              aux.add(new Brother(xmlBrother);
              xmlBrothers = utilXml.removeTagTreated(xmlBrothers, SUBOBJETOS[2]);
            this.setBrothers(aux);
          if (!xmlEducation.equals("")){
               this.setEducation(new Father(xmlEducation));     
}If the object is a leaf object, the constructor will be like this:
public class Mother {
     //Elements
     private String name;
     private String age;
     public Mother(String xml){          
          XmlUtil utilXml = new XmlUtil();
          HashMap objects = utilXml.parsearString(xml);
          ArraysList objectsList = new ArrayList();
          String[] Object = new String[2];
          this.setName((String)objects.get("Mother"));
          if (objects.get("attributes")!= null){
               objectsList = objects.get("attributes");
               for (int i = 0; i < objectsList.size();i++){
                 Object = objectsList.get(i);
                 if (object[0].equals("age"))
                   this.setAge(object[1]);
                 else
     }Each class will have its getter and setter but I do not have implemented in the examples.
Finally, the parser is as follows:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class XmlUtil {
     public HashMap parsearString(String contenido){
          HashMap objet = new HashMap();
          DocumentBuilderFactory factory;
          DocumentBuilder builder;
          Document document;
          try{
               if (content != null && !content.equals("")){
                    factory = DocumentBuilderFactory.newInstance();
                    builder = factory.newDocumentBuilder();
                    document = builder.parse(new ByteArrayInputStream(content.getBytes()));
                    object = visitNodes(document);                    
               }else{
                    object = null;
          } catch (ParserConfigurationException e) {
               e.printStackTrace();
               return null;
          } catch (SAXException e) {
               e.printStackTrace();
               return null;
          } catch (IOException e) {
               e.printStackTrace();
               return null;
          return object;
     private HashMap visitNodes (Node node){
          String nodeName = "";
          String nodeValue = "";
          ArrayList attributes = new ArrayList();
          HashMap object = new HashMap();
          Node childNode = node.getFirstChild();
          if (childNode.getNodeType() == Node.ELEMENT_NODE){
               nodeName = childNode.getNodeName();                    
               if (childNode.hasAttributes()){
                    attributes = visitAttributes(childNode.getAttributes());
               }else{
                    attributes = null;
               nodeValue = getNodeValue(childNode);
               object.put(nodeName, nodeValue);
               object.put("attributes", attributes);
          return object;
     private static String getNodeValue (Node node){          
          if (node.hasChildNodes() && node.getFirstChild().getNodeType() == Node.TEXT_NODE && !node.getFirstChild().getNodeValue().contains("\n\t"))
               return node.getFirstChild().getNodeValue();
          else
               return "";
     private ArrayList visitAttributes(NamedNodeMap attributes){
          Node node;
          ArrayList ListAttributes = new ArrayList();
          String [] attribute = new String[2];
          for(int i = 0; i < attributes.getLength(); i++){
               atribute = new String[2];
               node = attributes.item(i);
               if (node.getNodeType() == Node.ATTRIBUTE_NODE){
                    attribute[0] = node.getNodeName();
                    attribute[1] = node.getNodeValue();
                    ListAttributes.add(attribute);
          return ListAttributes;
}This code functioning properly. However, as exist around 400 objects to the xml, I wanted to create a method for more easily invoking objects that are below other and that's what I can't get to do at the moment.
The code I use is:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class UtilClasses {
     public Object UtilClasses(String package, String object, String xml){
          try {
            Class class = Class.forName(package + "." + object);
            //parameter types for methods
            Class[] partypes = new Class[]{Object.class};
            //Create method object . methodname and parameter types
            Method meth = class.getMethod(object, partypes);
            //parameter types for constructor
            Class[] constrpartypes = new Class[]{String.class};
            //Create constructor object . parameter types
            Constructor constr = claseObjeto.getConstructor(constrpartypes);
            //create instance
            Object obj = constr.newInstance(new String[]{xml});
            //Arguments to be passed into method
            Object[] arglist = new Object[]{xml};
            //invoke method!!
            String output = (String) meth.invoke(dummyto, arglist);
            System.out.println(output);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
          return null;
     }This is an example obtained from the Internet that I've wanted modified to my needs. The problem is that when the class calls this method to invoke the constructor and does not fail, this does not do what I expect, because it creates an empty constructor. If not, the parent class gives a casting error.
I hope that now have been more clear my intentions and that no one has fallen asleep reading this lengthy explanation.
greetings.

Similar Messages

  • How to parse contents from XML file in Java

    Hi All,
    I have a scenario like this . I have one xml file with key value pairs of ( name , URL ) . I have retrieved contents from XML file , now I want to parse these contents and store in a bean object.
    How to parse Contents of XML file??
    Thanks in advance,
    Rajendra.

    Hi All,
    I have a scenario like this . I have one xml file with key value pairs of ( name , URL ) . I have retrieved contents from XML file , now I want to parse these contents and store in a bean object.
    How to parse Contents of XML file??
    Thanks in advance,
    Rajendra.

  • How to read the contents of XML file from my java code

    All,
    I created an rtf report for one of my EBS reports. Now I want to email this report to several people. Using Tim's blog I implemented the email part. I am sending emails to myself based on the USERID logic.
    However I want to email to different people other then me. My email addresses are in the XML file.
    From the java program which sends the email, how can I read the fields from XML file. If any one has done this, Please point me to the right examples.
    Please let me know if there are any exmaples/BLOG's which explain how to do this(basically read the contents of XML file in the Java program).
    Thank You,
    Padma

    Ike,
    Do you have a sample. I am searched so much in this forum for samples. I looked on SAX Parser. I did not find any samples.
    Please help me.
    Thank you for your posting.
    Padma.

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

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

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

  • Non-blocking parsing of multiple xml files

    Hi there,
    I'm trying to parse multiple huge XML files concurrently for a query system over multiple xml streaming systems.
    For each huge xml file, I read them into the memory gradually (the new data would cover the old data in the buffer if the buffer is full). Two questions here:
    1. Do I have to set up a socket and write the buffered data to the socket in order to simuate that the parser can parse infinitely? It sounds not good to use socket across two threads just for the "infinite" nature.
    2. I want to simulate concurrently parsing multiple streams. A straightforward way is to have each parser sit in a thread. Is there any otherway that I can put all parsers in one thread and alternately call them? This requires that each individual parser could parse whatever they have seen so far rather and resume when they are called again.
    I'm curiously awaiting for your answers.
    thanks a lot,
    hong

    just taking a guess: create your own reader by extending java.io.Reader ; and let this reader taking care of fetching the data that the parser will use.

  • JAXB parsing an incomplete xml file

    hi folks,
    i am trying to parse a incomplete xml file (e.g some attribute and child elements are missing) in order to complete it via jaxb. however, parsing throws a SAXParseException (premature end of file), which interally is marked as unrecoverable, and a unmarshaller isn't capable of returning a result. not even the objects created so far.
    so my question is if there a way of getting the (incomplete) object tree no matter if the parsing was successfully or not. (i am aware of the fact, that this object tree might be invalid)
    cheer, johannes

    Thanks, works like a charm :)
    Another question.
    I have an index.jsp page with an HTML form (a simple "search" form, made of a text area and a submit button). Now, what I want to do is passing the parameter to two distinct servlets, each one dealing with a web service (one with ebay, the other one with last.fm).
    Unfortunately, in the action tag of the form only one value can be specified.
    Any suggestions?

  • Generating an XML representation of arbitrary Java objects

    Hi. Just for fun, I'm attempting to write some code which creates an XML representation of an arbitrary java object using reflection. The idea is that only properties with get/set methods should come through in the XML.
    Here is the code:
    package com.uhg.aarp.compas.persistence.common.xml;
    import java.io.IOException;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.w3c.dom.Document;
    import org.w3c.dom.DOMException;
    import org.w3c.dom.Node;
    import java.util.Stack;
    public class XMLDAO {
         public static String getXMLWithHeader(Object obj){
              return "<?xml version=\"0\"?>" + getXML(obj);
          * Returns an XML representation of an arbitrary object
         public static String getXML(Object obj){
              StringBuffer buffer = new StringBuffer();
              AccessorMethod[] accessorMethods = getAccessorMethods(obj);
              buffer.append("<" + obj.getClass().getName() + ">\n");
              //List
              if(obj instanceof List){
                   List objList = (List)obj;
                   Iterator iterator = objList.iterator();
                   while(iterator.hasNext()){                              
                        buffer.append(getXML(iterator.next()));
              else{
                   for(int i = 0; i < accessorMethods.length; i++){
                        Object fieldObj = null;
                        try{
                             fieldObj = accessorMethods.invoke();
                             1. Primitive Wrapper or String(base case)
                             if(fieldObj instanceof Integer || fieldObj instanceof Float || fieldObj instanceof Double
                                  || fieldObj instanceof Long || fieldObj instanceof String){
                                  buffer.append("<" + accessorMethods[i].getAccessorFieldName() + ">");
                                  buffer.append(accessorMethods[i].invoke());
                                  buffer.append("</" + accessorMethods[i].getAccessorFieldName() + ">\n");
                             else if(fieldObj instanceof Object[]){
                                  buffer.append("<" + accessorMethods[i].getAccessorFieldName() + ">\n");
                                  Object[] fieldArray = (Object[])fieldObj;
                                  for(int j = 0; j < fieldArray.length; j++)
                                       buffer.append(getXML(fieldArray[i]));
                                  buffer.append("</" + accessorMethods[i].getAccessorFieldName() + ">\n");
                        }catch(Exception e){
                             System.out.println("Couldn't invoke method: " + accessorMethods[i].getName());
              buffer.append("</" + obj.getClass().getName() + ">\n");
              return buffer.toString();
         * Returns the Object representation for the XML - used to rebuild Java objects
         * converted to XML by XMLDAO.getXML().
         public static Object getObject(String xmlString) throws ParserConfigurationException,
              SAXException, IOException{
              //the root element is the class name
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              DocumentBuilder builder = factory.newDocumentBuilder();
              Document document = builder.parse(xmlString);
              Stack objectStack = new Stack();
              return getObject(document);
         private static Object getObject(Node n){
              //every document is either an object or a bean property
              //all bean properties have values
              //no object has a value, it can only have bean properties
              //the base case occurs when the document has a value
              String nodeName = n.getNodeName();
              if(n.getNodeValue() == null){
                   System.out.println("node " + nodeName + " is an object");
              else{
                   System.out.println("node " + nodeName + " is a bean property");
              return null;
         * Returns all of the "getter" methods for the given object
         private static AccessorMethod[] getAccessorMethods(Object obj){
              Class theClass = obj.getClass();
              Method[] objMethods = theClass.getMethods();
              ArrayList methodList = new ArrayList();
              for(int i = 0; i < objMethods.length; i++){
                   try{
                        methodList.add(new AccessorMethod(obj, objMethods[i]));
                   }catch(IllegalArgumentException e){}
              return (AccessorMethod[])methodList.toArray(new AccessorMethod[methodList.size()]);
         * Invokes the specified "getter" method and returns the result as an Object
         private Object invokeAccessorMethod(Object obj, Method m) throws IllegalAccessException,
              InvocationTargetException{
              return m.invoke(obj, null);
    package com.uhg.aarp.compas.persistence.common.xml;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    * Represents an AccessorMethod (i.e. getField()) on an Object
    public class AccessorMethod{
         private Object obj;
         private Method m;
         private String accessorFieldName;
         * Constructor for AccessorMethod
         public AccessorMethod(Object obj, Method m) throws IllegalArgumentException{
              1. Method name starts with get
              2. Method name does not equal get
              3. Method takes no arguments
              4. Method return type is not void
              String methodName = m.getName();
              if(methodName.indexOf("get") != 0 || methodName.length() == 3 &&
                   m.getParameterTypes().length != 0 && m.getReturnType() != null){
                   throw new IllegalArgumentException("Not a valid getter method " + methodName);
              this.obj = obj;
              this.m = m;
              String tempName = m.getName().substring(3, m.getName().length());
              this.accessorFieldName = Character.toLowerCase(tempName.charAt(0)) + tempName.substring(1, tempName.length());
         public Object invoke() throws IllegalAccessException, InvocationTargetException{
              return m.invoke(obj, null);
         * Gets the m
         * @return Returns a Method
         public Method getM() {
              return m;
         * Sets the m
         * @param m The m to set
         public void setM(Method m) {
              this.m = m;
         * Gets the accessorFieldName
         * @return Returns a String
         public String getAccessorFieldName() {
              return accessorFieldName;
         * Sets the accessorFieldName
         * @param accessorFieldName The accessorFieldName to set
         public void setAccessorFieldName(String accessorFieldName) {
              this.accessorFieldName = accessorFieldName;
         * Gets the obj
         * @return Returns a Object
         public Object getObj() {
              return obj;
         * Sets the obj
         * @param obj The obj to set
         public void setObj(Object obj) {
              this.obj = obj;
         public String getName(){
              return this.m.getName();
    I'm having some trouble figuring out how to implement the XMLDAO.getObject(Node n) method. I was thinking of maintaining a Stack of the previous Objects as I traverse the DOM, but I think that might be unnecessary work. Basically I'm wondering how I determine what the last "object" is in the DOM from any given node. Anyone have any input?

    I think the end of my post got cut off:
    I'm having some trouble figuring out how to implement the XMLDAO.getObject(Node n) method. I was thinking of maintaining a Stack of the previous Objects as I traverse the DOM, but I think that might be unnecessary work. Basically I'm wondering how I determine what the last "object" is in the DOM from any given node. Anyone have any input?

  • Reg:Parsing of an xml file in Wed Dynpro for java

    Hi all,
    I have an Xml file in my local pc and i have to parse that xml file i.e in that xml file i have to get the values of some fields and i have to set those values to the attributes of a node.so can any one help me out in solving this issue.
    Thanks,
    Mahesh

    hi mahesh,
    check this link
    http://help.sap.com/saphelp_nw04s/helpdata/en/5d/d0e678bcf90e46bf31447e7f38c9d6/frameset.htm
    thanks and regrads
    bvr

  • Problem in parsing a particular XML file.

    Hello, I have an XML file like this:
    <eGov_IT:Intestazione xmlns:eGov_IT="http://www.cnipa.it/schemas/2003/eGovIT/Busta1_0/" xmlns:SOAP_ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.cnipa.it/schemas/2003/eGovIT/Busta1_0/
    E:\Progetti\EchoPorte\sviluppo\WEBCON~1\WEB-INF\risorse\Messaggio.xsd">
    <eGov_IT:IntestazioneMessaggio xmlns:eGov_IT="http://www.cnipa.it/schemas/2003/eGovIT/Busta1_0/">
    <eGov_IT:Collaborazione>PortaDelegata_PortaDiDominio_0000001_2007-10-05_12:26</eGov_IT:Collaborazione>
    <eGov_IT:Identificatore>PortaDelegata_PortaDiDominio_0000002_2007-10-05_12:26</eGov_IT:Identificatore>
    </eGov_IT:IntestazioneMessaggio>
    As you can see there are 2 elements in which the values are really similar. In fact in the Schema we use they have to match the same regular expression; here's the extract from my schema.
    <xsd:element name="Collaborazione" type="IdentificatoreType"/>
    <xsd:element name="Identificatore" type="IdentificatoreType"/>
    <xsd:simpleType name="IdentificatoreType">
    <xsd:restriction base="xsd:string">
    <xsd:pattern value="[\w]+_[\w]+_\d{7}_\d{4}\-\d{2}\-\d{2}_\d{2}:\d{2}"/>
    </xsd:restriction>
    </xsd:simpleType>
    I can CORRECTLY validate this expression using this code:
    public void validate (String doc, String schema) throws SAXParseException, SAXException
    try
    SchemaFactory schemaFactory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI );
    Schema schemaXSD = schemaFactory.newSchema( new File ( schema ) );
    Validator validator = schemaXSD.newValidator();
    DocumentBuilderFactory.newInstance().newDocumentBuilder();
    ByteArrayInputStream baisDoc = new ByteArrayInputStream(doc.getBytes());
    Document document = parser.parse(baisDoc);
    validator.validate( new DOMSource( document ) );
    And, in case the validation fails, I correctly gain a SAXParseException.
    The problem is that I can't understand if, in this case, the error is in the "Collaborazione" element or in the "Identificatore" element, because I get the following detailed message from the Exception:
    "cvc-pattern-valid: Value '' is not facet-valid with respect to pattern '[\w]+_[\w]+_\d{7}_\d{4}\-\d{2}\-\d{2}_\d{2}:\d{2}' for type 'IdentificatoreType'."
    How can I get more detailed informations about this error?
    Thanks everybody,
    Cris

    Check here:
    http://forum.java.sun.com/thread.jspa?threadID=5223284
    This is the correct post with my problem.
    Thanks!
    Cristiano

  • Pseudo code for DOM parsing a local XMl file

    HI all,
    1)     Can any body please provide me the JAVA pseudo code for parsing xml document from local mcahine and create another xml document in another location in loca machine with small transofrmations ? (JAVA mapping using DOM parsing tehnique using an xml file in loca machine using NWDS).
    2) Provide me with the links that can help me out to work with
    JAVA mapping using DOM
    Thanks,
    Ram.

    Hi,
    Have a Search in SDN with Keywords JAVA Mapping, & will get lot of stuff
    Implermenting JAVA Mapping in PI
    Implementing a Java Mapping in SAP PI
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/10dd67dd-a42b-2a10-2785-91c40ee56c0b
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/400ee77e-f9d6-2a10-2b8c-99281a4dcf6b
    Regards
    Seshagiri

  • Sax Parser for loading XML file

    We have a requirment by which we need to load huge XMl file in our DB everyday.
    THe XML file format is like --
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
    <emp>
    <ename>aaa</ename>
    <sal>3000</sal>
    </emp>
    <emp>
    <ename>bbb</ename>
    <sal>5000</sal>
    </emp>
    <dept>
    <name>productiong</name>
    <location>USA</location>
    <dept>
    I have written XMl SAX parser to load this file into DB -
    import org.xml.sax.helpers.DefaultHandler;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.XMLReader;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.Attributes;
    import java.io.*;
    import java.sql.*;
    import oracle.jdbc.driver.*;
    import oracle.xml.sql.*;
    import oracle.sql.*;
    import oracle.jdbc.*;
    import oracle.jdbc.pool.OracleDataSource;
    import java.util.*;
    public class test extends DefaultHandler
    String thisElement="";
    String table_name="";
    String table_name_2="";
    String sql="";
    String value_clause="";
    StringBuffer value_clauseBuffer;
    String Insert_sql="";
    int flag;
    String columnNames="";
    String questionmarks="";
    static String conStr = "jdbc:oracle:thin:@abcd1234:1521:dss501";
    static Connection conn;
    String arrayValues[] = new String[30];
    int j = 0;
    int emptyElementFlag = 0;
    public SurveyReader() throws SQLException, FileNotFoundException, IOException{
    DBConnect("username", "password");
    public static void DBConnect(String username, String password)
    throws SQLException, FileNotFoundException, IOException {
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    conn = DriverManager.getConnection(conStr, username, password);
    conn.setAutoCommit(true);
    public void startElement(String namespaceURI, String localName,
    String qName, Attributes atts) throws SAXException {
    thisElement = qName;
    if (thisElement!=table_name){
    columnNames = columnNames + ", " + qName;
    questionmarks = questionmarks +", " + "?";
    emptyElementFlag =0;
    public void characters(char[] ch, int start, int length)
    throws SAXException {
    if (thisElement !="root"){     
    if ((length == 0) && (thisElement !="") ){
    table_name = thisElement;
    sql = " Insert into "+ table_name +"(";
    value_clause="";
    value_clauseBuffer =null;
    columnNames = "";
    questionmarks ="";
    j =0;
    if ((length != 0) && (thisElement!="") && (thisElement!=table_name)){
    emptyElementFlag = 1;
    String s = new String(ch, start, length);
    String newString = s.replaceAll("'", "''");
    // String newString = s;
    if (value_clauseBuffer== null){
    value_clauseBuffer = new StringBuffer(newString);
    else{
    value_clauseBuffer.append(newString);
    public void endElement(String namespaceURI, String localName, String qName)
    throws SAXException {
    if (thisElement !="root"){
    if ((!(value_clauseBuffer == null))||((emptyElementFlag ==0) && (qName !=table_name))) {
    try{
    //value_clauseBuffer.append("', '");
    if (value_clauseBuffer == null){
    arrayValues[j]="";
    else{
    arrayValues[j]=""+value_clauseBuffer;
    j = j+1;
    value_clauseBuffer = null;
    emptyElementFlag =0;
    }catch(Exception e){
    System.err.println(e);
    System.exit(2);
    if (qName == table_name){
    if (!(value_clauseBuffer == null)){
    value_clause = "'"+value_clauseBuffer;
    columnNames =columnNames.substring(1, columnNames.length());
    int paramNumber = j;
    questionmarks =questionmarks.substring(1, questionmarks.length());
    sql = sql + columnNames + " ) values (" + questionmarks +"); ";
    Insert_sql=Insert_sql + sql;
    sql = "Begin "+sql + " End; ";
         try{
         PreparedStatement pstat = conn.prepareStatement(sql);
    for (int i=0; i<=j-1; i++ ){
    int k = i+1;
    pstat.setObject(k, arrayValues);
         ResultSet rset = pstat.executeQuery();
         rset.close();
         pstat.close();
    catch (Exception e) {
    System.err.println(e);
    System.out.print("sql " + sql);
    System.exit(1);
    table_name_2 = table_name;
    thisElement = "";
    public static void main (String args[]) {
    XMLReader xmlReader = null;
    System.out.println("Time " + new java.util.Date());
    try {
    SAXParserFactory spfactory = SAXParserFactory.newInstance();
    spfactory.setValidating(false);
    SAXParser saxParser = spfactory.newSAXParser();
    xmlReader = saxParser.getXMLReader();
    xmlReader.setContentHandler(new SurveyReader());
    xmlReader.setErrorHandler(new SurveyReader());
    InputSource source = new InputSource("short.xml");
    xmlReader.parse(source);
    conn.close();
    } catch (Exception e) {
    System.err.println(e);
    System.exit(1);
    This parser takes 2 hours to laod file of size around 8MB.
    ANy suggestions on improving performance of the parser.
    ANy other approach I should be taking to load this file into DB.
    We are using ORacle 9i DB with Character set UTF 8.
    Thanks!

    String buf = (new String(ch, start, length)).trim();
    if (thisElement != "root"){   
    if ((buf.length() == 0) && (thisElement !="") ){
    It run ok!
    Thanks 58871!
    Now, i want to export oracle table to xml file like :
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
    <emp>
    <ename>aaa</ename>
    <sal>3000</sal>
    </emp>
    <emp>
    <ename>bbb</ename>
    <sal>5000</sal>
    </emp>
    </root>
    Can SAX export to xml format?
    Pham Thanh Tung

  • Generate XML file dynamically using java

    Hi,
    I searched on this topic on the net and also in this forum but everything leads to parsing an existing file using JAXP technology. But i need to create an xml file dynamically from the data coming from a different source. I can do it manually by writting the content to a file. But i am sure there is a better way for it. I would be obliged if some one could give me and example java class which produces a simple xml file or direct me to any resource online.
    Thank you in advance.

    Yes you can create the xml file dynamically. Like this,
    BufferedWriter bw = new BufferedWriter(new FileWriter("xyz.xml"));
    bw.write(buffer.toString()); //where buffer is StringBuffer whcih contains the your xml data
    bw.close();
    Remember to close the BufferedWriter, otherwise it will create the file but don't write anything.
    Hope this will help u.
    ....yogesh

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

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

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

  • Trying to parse a huge XML file

    I'm trying to parse a large (~200 Meg) XML file. I get out of memory errors with DOM, and so far using SAX has been a huge disaster. My program has to run on IE and Netscape as an applet. I've run into a HUGE amount of errors. While I have been doing Java programming for about 2 years, this is the first time I've ever worked with XML. The error I am currently getting is an abstract method error associated with the following code :
    SAXParserFactory spf = new
                             com.sun.xml.parser.SAXParserFactoryImpl();
                   spf.setValidating(false);
                   try {
                   out.write("Gets past SAXParserFactory creation");
                   out.flush();
                        catch (Exception e) {}
                   xmlReader = null;
                   try {
                             // Create a JAXP SAXParser
                             saxParser = spf.newSAXParser();
                             // Get the encapsulated SAX XMLReader
                             out.write("gets to assigning an XMLReader");
    ***THIS LINE OF CODE ***                         xmlReader = saxParser.getXMLReader();
                             out.write("gets past assigning an XMLReader");
                             out.flush();
    I've run out of ideas and would greatly appreciate any help anyone could offer on this most frustrating problem.

    With XML, we don't have to check each line of the file, only the data in those tags of each element that we are searching on.That's true, once you have read the entire XML and parsed it. Reading the entire XML would of course take much longer than reading the text file it was generated from, so you would want to pre-parse it into a DOM and store that somehow. But then to do a search you'd have to load that DOM, which is in turn much larger than the XML it was generated from...
    What you describe sounds to me a lot like a database application. Of course I don't know anything about the specifics of what you are doing with the text, but storing it in a database with indexes that support the searches seems to me like a better approach. Of course you then have the challenge of distributing the database and its supporting software in a form that doesn't require installation. But I'd respectfully suggest that banning any installation at all is a bit extreme. After all, where I live you can buy an encyclopedia on a CD, from a gas station, for $10. And when you load the CD, it runs through an installation procedure. No big deal these days.

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

Maybe you are looking for