cancel
Showing results for 
Search instead for 
Did you mean: 

converting context-tree to xml?

achim_hauck2
Active Contributor
0 Kudos

hi there,

i want to convert a context-tree in xml. i think, this is a very common situation and there should be some ready-to-use interfaces, classes, etc.

but i couldn't find any at the moment.

do i really have to traverse my context node for node, element for element and build a DOM-tree on my own?

what would be the best way for traversing the context in this case?

kr, achim

Accepted Solutions (1)

Accepted Solutions (1)

Former Member
0 Kudos

Pran,

<i>Can we consider using the wdContext object as the input for the ContextReader and then use the

IWDNodeInfo rootNodInfo = wdContext.getNodeInfo();

Iterator iter = rootNodInfo.iterateChildren();

to obtain an iteration of NodeInfo objects from which we can derive the IWDNode object.</i>

If you mean passing wdContext node directly as argument to serializer, then the answer is "NO": immediate children of wdContext are ALL singleton nodes and call to parentNode.getChild( "NODE", idx ) will fail.

You may modify parseNode method in ContextReader to follow singleton nodes not by index

but rather by current selection.

Regards,

VS

Former Member
0 Kudos

Oops!

Just try to test -- and it works out of the box.

So you can pass wdContext and serialize complete context graph.

VS

Former Member
0 Kudos

Hi Valery

sometimes the code does more than it is supposed to do .. thanks Valery but I cant give you any points here

Regards

Pran

achim_hauck2
Active Contributor
0 Kudos

<i>.. thanks Valery but I cant give you any points here</i>

yeah, that's my part. i just wanted to try/adapt the code before i give points. but i consider the code as "problem solved" (without trying it yet...

kr, achim

Former Member
0 Kudos

Hi Valery Silaev,

your code is fantastic... but have a little problem, don't work correctly with recursive nodes..... I will try to modify it, but I'm new in XML programming

Answers (3)

Answers (3)

Former Member
0 Kudos

Hi Pradeep!!

I tried to use Valery's code but got a lot of errors.

What jar files do i have to add to my WD java build path??

Thanx again!!!!!

Former Member
0 Kudos

Hi Valery

Can we consider using the wdContext object as the input for the ContextReader and then use the

IWDNodeInfo rootNodInfo = wdContext.getNodeInfo();

Iterator iter = rootNodInfo.iterateChildren();

to obtain an iteration of NodeInfo objects from which we can derive the IWDNode object.


  public ContextReader(final IWDNode root) 
  {
    if ( null == root )
      throw new IllegalArgumentException
      (
        "NULL supplied as root for serialization"
      );
      _root = root;
  }

I used a rough code for my project though not advanced as the above but helps basic debug if sourced to the logger APIs


		IWDNodeInfo rootNodInfo = wdContext.getNodeInfo();
		Iterator iter = rootNodInfo.iterateChildren();
		String strXML = null;
		while (iter.hasNext()) {
			NodeInfo iwdNodeInfo = (NodeInfo) iter.next();

			//pass the NodeInfo and the 
			strXML =
				iterateAndDisplay(
					iwdNodeInfo,
					wdContext.getChildNode(iwdNode.getName(), 0));
		}
		FileOutputStream fileOut = null;
		byte[] bt = ("<context>"+strXML+"</context>").getBytes();
		try {

			fileOut = new FileOutputStream(new File("C:\value.txt"), false);
			fileOut.write(bt);
			fileOut.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}





	public String iterateAndDisplay(
		com.sap.tc.webdynpro.progmodel.context.NodeInfo nodeInfo,
		com.sap.tc.webdynpro.progmodel.api.IWDNode actualNode) {
		//@@begin iterateAndDisplay()
		Iterator iterChild = nodeInfo.iterateChildren();
		Iterator iterAttributes = nodeInfo.iterateAttributes();
		ArrayList arrListAttrib = new ArrayList();
		//storing attribute names in an Arraylist 
		while (iterAttributes.hasNext()) {
			arrListAttrib.add(
				((AttributeInfo) iterAttributes.next()).getName());
		}

		xmlString.append("<" + nodeInfo.getName() + ">n");
		//if multiple objects present for the node 
		for (int i = 0; i < actualNode.size(); i++) {
			for (int j = 0; j < arrListAttrib.size(); j++) {
				String attrName = (String) arrListAttrib.get(j);
				//append attribute name 
				xmlString.append("<" + attrName + ">");
				//obtain IWDNodeElement object to obtain Attribute object
				//IWDNode childNode = wdContext.getChildNode(node.getPathDescription(), 0);
				IWDNodeElement actualNodeElement = actualNode.getElementAt(i);
				String strAttrValue =
					actualNodeElement.getAttributeValue(attrName) + "";
				xmlString.append(strAttrValue);
				xmlString.append("</" + attrName + ">n");
				//			}
			}
		}
		while (iterChild.hasNext()) {
			NodeInfo iwdNode = (NodeInfo) iterChild.next();
			iterateAndDisplay(
				iwdNode,
				actualNode.getChildNode(iwdNode.getName(), 0));
		}
		xmlString.append("</" + node.getName() + ">n");
		return xmlString.toString();

		//@@end
	}

Former Member
0 Kudos

You should probably implement a variant of the visitor pattern, that uses the generic context API.

Armin

achim_hauck2
Active Contributor
0 Kudos

Armin,

good suggestion. but isn't this (converting a context-tree to xml) a quite common task?

isn't there any helper-class provided by sap (traversing the tree somehow)?

iterating the nodes isn't probiate, because i don't know at design time, how deep the hierarchy of the nodes is.

well, otherwise i have to write the visitor on my own...

kr, achim

Former Member
0 Kudos

Hi,

There is really a reason why there are no such classes -- it's very hard to get agreed on format

Below is my 1-hour attempt for this problem, it can serialize any node in generic format along with all subnodes (subnodes should be non-singletons, thoughts).

Here is file <b>net.sdn.wdextras.context.xml.ContextReader</b>:

package net.sdn.wdextras.context.xml;

import java.io.IOException;

import java.util.Iterator;
import java.util.Map;
import java.util.IdentityHashMap;
import java.util.Collections;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;

import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.XMLFilterImpl;

import com.sap.dictionary.runtime.BuiltInTypeEnum;
import com.sap.dictionary.runtime.IDataType;
import com.sap.dictionary.runtime.ISimpleType;

import com.sap.tc.webdynpro.progmodel.api.IWDAttributeInfo;
import com.sap.tc.webdynpro.progmodel.api.IWDNode;
import com.sap.tc.webdynpro.progmodel.api.IWDNodeElement;
import com.sap.tc.webdynpro.progmodel.api.IWDNodeInfo;
/**
 * @author Valery_Silaev
 * Code based on sample from
 * Processing XML with Java
 * by Elliotte Rusty Harold
 * see <a href="www.cafeconleche.org/books/xmljava/chapters/ch08s05.html" TARGET="test_blank">www.cafeconleche.org/books/xmljava/chapters/ch08s05.html</a>
 */

class ContextReader extends XMLFilterImpl 
{
  final IWDNode _root;
	
  public ContextReader(final IWDNode root) 
  {
    if ( null == root )
      throw new IllegalArgumentException
      (
        "NULL supplied as root for serialization"
      );
      _root = root;
  }
	
  public void setProperty (final String name, final Object value)
    throws SAXNotRecognizedException, SAXNotSupportedException
  {	
    /*
     * We need to ignore declaration handler settings
     * for SAX parser
     */
  }

  public void parse(final InputSource in) 
    throws SAXException, IOException, UnsupportedOperationException 
  {
    startDocument();
    startPrefixMapping( "wdp", NS_WDP ); 		
    startPrefixMapping( "xsi", NS_XSI );
    startPrefixMapping( "xsd", NS_XSD );		
    
    parseNode( _root );
    
    endPrefixMapping( "xsd" );
    endPrefixMapping( "xsi" );
    endPrefixMapping( "wdp" );		
    endDocument();
  }
  
  protected void parseElement(final IWDNodeElement element) throws SAXException, IOException
  {
    final IWDNode     node = element.node();
    final IWDNodeInfo meta = node.getNodeInfo();
		
    final int idx = element.index();  
    final AttributesImpl elementAttrs = new AttributesImpl();
		
    if ( node.isMultiSelected(idx) )
      elementAttrs.addAttribute
      ( 
        NS_WDP, "selected", "wdp:selected", "NMTOKEN", "true"  
      );

    startElement( NS_WDP, "element", "wdp:element", elementAttrs );
				
    for (final Iterator i = meta.iterateAttributes(); i.hasNext(); )
    {
      final IWDAttributeInfo wdAttr = (IWDAttributeInfo)i.next();
			
      final IDataType wdType = wdAttr.getDataType();
      if ( !wdType.isSimpleType() )
        throw new IllegalArgumentException("Have no clue how to serialize non-simple types");
				
      final ISimpleType wdSimpleType = (ISimpleType)wdType;
			
      final AttributesImpl xmlAttributes = new AttributesImpl();
      xmlAttributes.addAttribute( NS_XSI, "type", "xsi:type", "NMTOKEN", getSchemaType( wdSimpleType ) );		
      xmlAttributes.addAttribute( NS_WDP, "name", "wdp:name", "NMTOKEN", wdAttr.getName() );
			
      final Object wdValue  = element.getAttributeValue( wdAttr.getName() );
      if ( wdValue == null )
      {
        xmlAttributes.addAttribute( NS_XSI, "nil", "xsi:nil", "NMTOKEN", "true" );
        startElement( NS_WDP, "attribute", "wdp:attribute", xmlAttributes );
        endElement( NS_WDP, "attribute", "wdp:attribute" );
      }
      else
      {
        final String xmlValue = wdSimpleType.toString( wdValue );
        startElement( NS_WDP, "attribute", "wdp:attribute", xmlAttributes );
        final char[] content = xmlValue.toCharArray();
        characters( content, 0, content.length );
        endElement( NS_WDP, "attribute", "wdp:attribute" );
      }
    }
    for (final Iterator i = meta.iterateChildren(); i.hasNext(); )
    {
      final IWDNodeInfo childMeta = (IWDNodeInfo)i.next();
      final IWDNode     childNode = node.getChildNode( childMeta.getName(), idx );
      parseNode( childNode );
    }
    endElement( NS_WDP, "element", "wdp:element");
  }
	
  protected void parseNode(final IWDNode node) throws SAXException, IOException
  {
    final AttributesImpl xmlAttrs = new AttributesImpl();
		xmlAttrs.addAttribute( NS_WDP, "name", "wdp:name", "NMTOKEN", node.getNodeInfo().getName() );
    xmlAttrs.addAttribute( NS_WDP, "selection", "wdp:selection", "NMTOKEN", Integer.toString( node.getLeadSelection() ) );
		
    if ( node == _root)
      xmlAttrs.addAttribute( NS_XSI, "documentation", "xsi:documentation", "NMTOKEN", 
      "Serialized context");
		
    startElement( NS_WDP, "node", "wdp:node", xmlAttrs );
    for (int idx = 0, size = node.size(); idx < size; idx++)
    {
      parseElement( node.getElementAt( idx ) );
    }
    endElement( NS_WDP, "node", "wdp:node" );
  }	

  public static String getSchemaType(final ISimpleType type) 
  {
    return (String)DDIC2XSD.get( type.getBuiltInTypeEnum() );
  }
  	
  final private static Map DDIC2XSD;
  static
  {
    final Map mapping = new IdentityHashMap();
    mapping.put( BuiltInTypeEnum.TYPE_STRING,    "xsd:string" );
    mapping.put( BuiltInTypeEnum.TYPE_BINARY,    "xsd:base64Binary");
    mapping.put( BuiltInTypeEnum.TYPE_DATE,      "xsd:date" );
    mapping.put( BuiltInTypeEnum.TYPE_TIME,      "xsd:time");
    mapping.put( BuiltInTypeEnum.TYPE_TIMESTAMP, "xsd:dateTime" );
    mapping.put( BuiltInTypeEnum.TYPE_BOOLEAN,   "xsd:boolean" );
    mapping.put( BuiltInTypeEnum.TYPE_DOUBLE,    "xsd:double" );
    mapping.put( BuiltInTypeEnum.TYPE_INTEGER,   "xsd:int" );
    mapping.put( BuiltInTypeEnum.TYPE_DECIMAL,   "xsd:decimal" );
    mapping.put( BuiltInTypeEnum.TYPE_FLOAT,     "xsd:decimal" );
    mapping.put( BuiltInTypeEnum.TYPE_LONG,      "xsd:long" );
    mapping.put( BuiltInTypeEnum.TYPE_SHORT,     "xsd:short" );
    DDIC2XSD = Collections.unmodifiableMap( mapping );
  }
  final private static String NS_WDP = "http://www.sap.com/solutions/netweaver/webdynpro";
  final private static String NS_XSI = "http://www.w3.org/2001/XMLSchema-instance";
  final private static String NS_XSD = "http://www.w3.org/2001/XMLSchema";
}

Next, file <b>net.sdn.wdextras.context.xml.XmlSerializer</b>:


package net.sdn.wdextras.context.xml;

import java.io.Writer;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerConfigurationException;

import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;

import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

import com.sap.tc.webdynpro.progmodel.api.IWDNode;

/**
 * @author Valery_Silaev
 */
public class XmlSerializer 
{
  final private Templates _templates;
	
  public XmlSerializer(  )
  {	
    _templates = null;
  }
	
  public XmlSerializer( Templates xslt )
  {
    _templates = xslt;
  }
	
  public void serialize( IWDNode root, Writer out ) throws Exception
  {
    final Transformer transformer;			
    if ( null == _templates )
      transformer = identityTransformation();
    else
      transformer = _templates.newTransformer();

    final BufferedWriter writer = new BufferedWriter(out);
    final Source source = new SAXSource( new ContextReader(root), new VoidInputSource() ); 
    final Result result = new StreamResult( out );
		
    transformer.transform( source, result );
    writer.flush();
  }
	
  public static Transformer identityTransformation()
  {
    final TransformerFactory factory = TransformerFactory.newInstance();
    try
    {
      return factory.newTransformer();
    }
    catch (final TransformerConfigurationException exOnCreateTransformer)
    {
      throw new RuntimeException( exOnCreateTransformer );
    }
  }

  final private static class VoidInputSource extends InputSource
  {
    VoidInputSource()
    {
	super( new ByteArrayInputStream(NO_DATA) );
    }
		
    final private static byte[  ] NO_DATA = {};
  }
	
}

Sample usage:

final XmlSerializer serializer = new XmlSerializer();
final StringWriter out = new StringWriter();
serializer.serialize( wdContext.nodeEmployee(), out );
wdContext.currentContextElement().setSerializedResult( out.toString() );

You can optionally create serializer with different XSL template to change output format.

Feel free to use / change. Today I release code under BSD license

Regards,

VS

0 Kudos

Hello Valery,

based on your wonderful Code we (Marco Hochstrasser) have implemented a ContextWriter to write the Output from your ContextReader back into Nodes. This could be interesting eg. in a GuidedProcedures environment for transferring Data between WD-Applications.

/*
 * ContextWriter.java       25.03.2008
 *
 * Copyright (c) 2008 BIT, Monbijoustrasse 74, 3001 Bern
 * All rights reserved.
 */

package ch.admin.bc.utils.wdy.XMLContextConverter;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Stack;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

import com.sap.tc.webdynpro.progmodel.api.IWDNode;
import com.sap.tc.webdynpro.progmodel.api.IWDNodeElement;
import com.sap.tc.webdynpro.progmodel.api.IWDNodeInfo;

/**
 * Klasse fuer das abfuellen eines Node mit Hilfe eines
 * XML-Inputs welcher mit dem ContextReader resp. der XMLSerializer erstellt wurde.
 * 
 * @version 0.1 %I%, %G%
 */
public class ContextWriter implements ContentHandler {
    
    
    private ArrayList nodeList = new ArrayList();
    private int elementCounter = 0;

    private IWDNodeElement currentElement;
    private String currentAttribute;
    private Object currentContent;
    private String currentAttributeType;
    
    private Stack oldNodesStack = new Stack();
    private Stack elementCounterStack = new Stack();

    private IWDNode rootNode;
    private IWDNode currentNode;

    /**
     * Konstruktor
     * @param node zu füllende Root-Node
     */
    public ContextWriter(IWDNode node) {
        rootNode = node;
    }

    /* (non-Javadoc)
     * @see org.xml.sax.ContentHandler#endDocument()
     */
    public void endDocument() throws SAXException {
        /*
         * Wird nicht verwendet
         * (ueberschriebene Methode des ContentHandler
         */
    }

    /* (non-Javadoc)
     * @see org.xml.sax.ContentHandler#startDocument()
     */
    public void startDocument() throws SAXException {
        /*
         * Wird nicht verwendet
         * (ueberschriebene Methode des ContentHandler
         */
    }

    /**
     * Inhalt des Elements wird im char-array uebergeben
     * Dabei wird die eigentliche Value des XML-Elementes ausgelesen.
     * <p>
     * Bei folgendem XML-Element waere "Test1" der Inhalt, mit length 5
     * <wdp:attribute xsi:type="xsd:string" wdp:name="Stringattribut1">Test1</wdp:attribute>
     * 
     * @param ch Character
     * @param start des Inhaltes
     * @param length Laenge des Inhaltes
     */
    public void characters(char[] ch, int start, int length) throws SAXException {
        /*
         * Hole Content 
         */
        String tempContent = new String(ch, start, length);
        
        /*
         * Wenn Attribute gesetzt (also nicht ein wdp:element oder ein wdp:node)
         */
        currentContent = null;
        
        if (!currentAttributeType.equals("")) {
            /*
             * Abfangen der einzelnen Attribut-Typen und zuweisen
             * des Inhaltes
             */
            if (currentAttributeType.equals("xsd:string")) {
                /* String */
                currentContent = tempContent;
                
            } else if (currentAttributeType.equals("xsd:base64Binary")) {
                /* Byte - funktioniert nicht bei Zahlwerten */
                currentContent = tempContent.getBytes();
                
            } else if (currentAttributeType.equals("xsd:date")) {
                /* Date */
                SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    currentContent = new Date(formater.parse(tempContent).getTime());
                } catch (ParseException e) {
                    currentContent = new Date(0);
                }
                
            } else if (currentAttributeType.equals("xsd:time")) {
                /* Time */
                SimpleDateFormat formater = new SimpleDateFormat("HH:mm:ss");
                try {
                    currentContent = new Time(formater.parse(tempContent).getTime());
                } catch (ParseException e) {
                    currentContent = new Time(0);
                }
                
            } else if (currentAttributeType.equals("xsd:dateTime")) {
                /* Datetime */
                SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
                try {
                    currentContent = new Timestamp(formater.parse(tempContent).getTime());
                } catch (ParseException e) {
                    currentContent = new Timestamp(0);
                }
                
            } else if (currentAttributeType.equals("xsd:boolean")) {
                /* Boolean */
                currentContent = new Boolean(tempContent);
                
            } else if (currentAttributeType.equals("xsd:double")) {
                /* Double */
                currentContent = new Double(tempContent);
                
            } else if (currentAttributeType.equals("xsd:int")) {
                /* Integer */
                try {
                    currentContent = new Integer(Integer.parseInt(tempContent));
                } catch (NumberFormatException e) {
                    currentContent = new Integer(0);
                }
                
            } else if (currentAttributeType.equals("xsd:decimal")) {
                /* Decimal */
                currentContent = new BigDecimal(tempContent);
                
            } else if (currentAttributeType.equals("xsd:float")) {
                /* Float */ 
                currentContent = new BigDecimal(tempContent);
                
            } else if (currentAttributeType.equals("xsd:long")) {
                /* Long */
                currentContent = new Long(tempContent);
                
            } else if (currentAttributeType.equals("xsd:short")) {
                /* Short */ 
                currentContent = new Short(tempContent);
                
            }
        }
    }

    /* (non-Javadoc)
     * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int)
     */
    public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
        /*
         * Wird nicht verwendet
         * (ueberschriebene Methode des ContentHandler
         */

    }

    /* (non-Javadoc)
     * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String)
     */
    public void endPrefixMapping(String prefix) throws SAXException {
        /*
         * Wird nicht verwendet
         * (ueberschriebene Methode des ContentHandler
         */

    }

    /* (non-Javadoc)
     * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String)
     */
    public void skippedEntity(String name) throws SAXException {
        /*
         * Wird nicht verwendet
         * (ueberschriebene Methode des ContentHandler
         */

    }

    /* (non-Javadoc)
     * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator)
     */
    public void setDocumentLocator(Locator locator) {
        /*
         * Wird nicht verwendet
         * (ueberschriebene Methode des ContentHandler
         */

    }

    /* (non-Javadoc)
     * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String)
     */
    public void processingInstruction(String target, String data) throws SAXException {
        /*
         * Wird nicht verwendet
         * (ueberschriebene Methode des ContentHandler
         */

    }

    /* (non-Javadoc)
     * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String)
     */
    public void startPrefixMapping(String prefix, String uri) throws SAXException {
        /*
         * Wird nicht verwendet
         * (ueberschriebene Methode des ContentHandler
         */

    }

    /**
     * Element wird abgeschlossen 
     * also mit z.B. </wdp:attribute> beendet.
     * 
     * @param namespaceURI Namesumgebung
     * @param localName Name
     * @param qName
     */
    public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
        /*
         * Pruefen ob ein Attribut forhanden ist
         * nur dann handelt es sich um ein Attribut, welches gesetzt werden kann.
         */
        if (currentAttribute != null && currentContent != null) {
            try{
                currentElement.setAttributeValue(currentAttribute, currentContent);
            }catch(ClassCastException ec){
                // ClassCast Exception, catch without return..
            }
            currentAttribute = null;
        }
        
        /*
         * Ein neues Element, der counter wird erhoeht
         */
        if(qName.equals("wdp:element")){
            elementCounter++;
        }
        
        /*
         * Ein neuer node (Node im Node), CurrentNode wird definiert und
         * der Stack gefuellt
         */
        if (qName.equals("wdp:node")) {
            if(!oldNodesStack.isEmpty()){
                currentNode = (IWDNode) oldNodesStack.pop();
                
                elementCounter = ((Integer)elementCounterStack.pop()).intValue();
                
            }else{
                currentNode = rootNode;
            }
        }

    }

    /**
     * Element wird gelesen
     * z.B. mit <wdp:attribute>
     * 
     * @param namespaceURI Namesumgebung
     * @param localName Name
     * @param qName
     * @param atts Attribute des Elements
     */
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        
        /*
         * Node wird abgefangen
         */
        if (qName.equals("wdp:node")) {
            /*
             * Hole den Node Namen
             */
            String nodeName ="";
            for (int i = 0; i < atts.getLength(); i++) {
                if (atts.getQName(i) != null) {
                    if (atts.getQName(i).equals("wdp:name")) {
                        nodeName =  atts.getValue(i);
                        i = atts.getLength();
                    }
                    
                }
            }
            /*
             * Setzte das Node auf den "currentNode"
             */
            if(rootNode.getNodeInfo().getName().equals(nodeName)){
                currentNode = rootNode;
                
            }else{
                /*
                 * Durchsuche alle Nodes und Unternodes rekursiv
                 * mit der searchForChildNodes Methode
                 */
                 oldNodesStack.push(currentNode);
                 elementCounterStack.push(new Integer(elementCounter));
                 currentNode = searchForChildNodes(rootNode, nodeName, elementCounter);             
                 elementCounter = 0;
            }
            
        /*
         * Elemente werden abgefangen
         */
        } else if (qName.equals("wdp:element")) {

            /*
             * Ein neues Element wird im currentNode erstellt 
             */
            IWDNodeElement element = currentNode.createElement();
            currentNode.addElement(element);
            currentElement = element;
            /*
             * Bei neuem Elemement werden die Attribut-Inhalte geloescht
             */
            currentAttribute = null;
            currentContent = null;
            
        /*
         * Attribut wird abgfangen
         */
        } else if (qName.equals("wdp:attribute")) {
            /*
             * Lese den Typ sowie den Namen des Attributes
             */
            String varName = "";
            String content;
            for (int i = 0; i < atts.getLength(); i++) {
                if (atts.getQName(i) != null) {

                    try {
                        if (atts.getQName(i).equals("xsi:type")) {
                            currentAttributeType = atts.getValue(i);
                        }
                        if (atts.getQName(i).equals("wdp:name")) {
                            currentAttribute = atts.getValue(i);
                        }
                    } catch (Exception e) {
                        // Fehler bei der Zuweisung werden ignoriert
                    }
                }
            }
        }
    }
    /**
     * Suche rekursiv nach weiteren Nodes. 
     * Dadurch ist es moeglich ein Node in der Node auch 
     * abzugleichen (dieser darf jedoch nicht singleton sein!)
     * 
     * @param rootNode
     * @param searchedNode Name des zu suchenden Nodes
     * @param idx Nummer des Elements des Obernodes
     * @return Gefundene Node
     */
    private IWDNode searchForChildNodes(IWDNode rootNode, String searchedNode, int idx){
        /*
         * Durchsuche alle Nodes und Unternodes rekursiv
         */
         for(final Iterator i = rootNode.getNodeInfo().iterateChildren(); i.hasNext();){
             final IWDNodeInfo childMeta = (IWDNodeInfo) i.next();
             final IWDNode childNode = rootNode.getChildNode(childMeta.getName(), idx);
             
             /*
              * Wenn der Nodename stimmt, ansonsten wird eine Ebene tiefer gesucht
              */
             if(childNode.getNodeInfo().getName().equals(searchedNode)){
                 return childNode;
             }else{
                 IWDNode smallChildNode = searchForChildNodes(childNode, searchedNode, idx);
                 if(smallChildNode!=null){
                     return smallChildNode;
                 }
             }
               
         }
         
         return null;
    }

}

Regards,

Manuel

Former Member
0 Kudos

Could you please add this into the Wiki? That would be great!

Armin