Xslt node recursion

have the following xml
<level levelID="00" checked="false">
     <director>Jeff</director>
     <level levelID="11" checked="false">
          <director>John</director>
          <level levelID="22" checked="false">
               <director>Bob</director>
               <client levelID="33" checked="false">
                    <manager/>
               </client>
               <client levelID="44" checked="false">
                    <manager/>
               </client>
          </level>
          <level levelID="55" checked="false">
               <director>Rick</director>
               <client levelID="66" checked="false">
                    <manager>Joe</manager>
               </client>
          </level>
          <level levelID="77" checked="false">
               <director>Alex</director>
               <client levelID="88" checked="false">
                    <manager/>
               </client>
          </level>
          <level levelID="99" checked="false">
               <director>Brian</director>
               <client levelID="0101" checked="false">
                    <manager>Ricky</manager>
               </client>
          </level>
         </level>I was wondering if someone would have some sample recursive xslt code that would allow me to visit all level elements.
Thank you for your time

If so, is your input file is xml file ? If the file is not an xml file , then you need to do content conversion in the sender file adapter. Now question is , file is always a flat structure. So if you want to convert your non xml input file(i.e coma separated etc) into xml file in your file adapter into the deeply nested structure as you mentioned, it is difficult . I mean to say content conversion will not give you the structure more than 2 levels...
<i><i>Can we loop through a recursive source structure via Java Mapping? Have you done something like that?</i></i>
>>>Yes .Source structure is flat message structure...for a file it does not matter having deeply nested structure..
Regards,
Moorthy

Similar Messages

  • Scene Graph traversal. Getting all the children of a node recursively

    Hi,
    Requirement: To resize all the controls of a scene (including controls that contain text like label, button) as per the scene size
    Approach: To implement the above requirement (see code snippet below), I added Listeners for width and height properties of a Scene and whenever the scene size changes, I get all the children of the root node of the scene and invoked the setScaleX() and setScaleY() for the children.
    Problem: In my design, labels and buttons are wrapped inside VBox, HBox etc. Method getChildrenUnmodifiable() returns only the first level of children and hence my HBox and VBox are getting scaled as per the scene size but not the children of VBox and HBox. Is there a built-in function to get all the children of a node recursively ? Or what is the best way to resize text as the scene size changes ?
    Scene mainScene = new Scene(borderPane, PERMANENT_WIDTH,
                    PERMANENT_HEIGHT, Color.HONEYDEW);
    rootNode = mainScene.getRoot();
            mainScene.widthProperty().addListener(new ChangeListener() {
                @Override
                public void changed(ObservableValue observable, Object oldValue,
                        Object newValue) {
                    Double widthScalingFactor = ((Double) newValue) / PERMANENT_WIDTH;
                     ObservableList<Node> children = rootNode.getChildrenUnmodifiable();
                    for (Node child : children) {
                        child.setScaleX(widthScalingFactor);
            mainScene.heightProperty().addListener(new ChangeListener() {
                @Override
                public void changed(ObservableValue observable, Object oldValue,
                        Object newValue) {
                    Double heightScalingFactor = ((Double) newValue) / PERMANENT_HEIGHT;
                    ObservableList<Node> children = rootNode.getChildrenUnmodifiable();
                    for (Node child : children) {
                        child.setScaleY(heightScalingFactor);
            });Thanks.

    Added the following code to get all the children recursively. now the scaling is applied to all nodes of a scene.
        private static void getChildren(Parent parentNode) {
            if (parentNode.getChildrenUnmodifiable().size() != 0) {
                ObservableList<Node> tempChildren = parentNode
                        .getChildrenUnmodifiable();
                allChildren.addAll(tempChildren);
                for (Node n : tempChildren)
                    getChildren((Parent) n);
            } else
                allChildren.add(parentNode);
        }

  • Workflow to move pages to selected language nodes recursively

    I have a need to create a workflow to move a content node recursively to selected language nodes. Can you refer me some example of this? Thanks!

    You can also use recommended CQ roll out feature for this.
    Yogesh

  • XSLT+XPath Recursion

    I want to ask you to help me. I have problem with next task :
    Input data :
    Input data : build.xml
    <project name="name of project" default="compile" basedir=".">
    <target name="all" depends="clean,compile"
    description="Clean build and dist directories, then compile"/>
    <target name="clean"
    description="Delete old build and dist directories">
    </target>
    <target name="compile" depends="prepare"
    description="Compile Java sources">
    </target>
    <target name="dist" depends="compile,javadoc"
    description="Create binary distribution">
    </target>
    <target name="install" depends="compile"
    </target>
    <target name="javadoc" depends="compile"
    description="Create Javadoc API documentation">
    </target>
    <target name="list"
    </target>
    <target name="prepare">
    </target>
    </project>
    Me should build table of dependency using XSLT+XPath
    Target Dependencies
    clean
    list
    prepare
    all ______ clean
    ________ compile
    __________ - prepare
    compile | prepare
    dist ______ compile
    ___________ - prepare
    javadoc
    - compile
    - prepare
    install ____ compile
    __________ -prepare
    javadoc ___ compile
    ___________ -prepare
    I have read article and done example (http://www.ibm.com/developerworks/xml/library/x-xslrecur/ )
    Could you help me, please ?
    My source :
    <!-- -->
    <tr style="background-color: gray;">
    <td align="center">TARGET DEPENDENCY</td>
    </tr>
    <tr>
    <td width="100%">
    <table border="1"
    class="targetDependencyANT" align="center">
    <tr>
    <td
    style="background-color: olive">
    Target
    </td>
    <td
    style="background-color: olive">
    Dependencies
    </td>
    </tr>
    <xsl:call-template
    name="printEmptyTarget" />
    <xsl:call-template
    name="printNotEmptyTarget" />
    </table>
    </td>
    </tr>
    <xsl:template name="printEmptyTarget">
    <xsl:for-each select="project/target[not(@depends)]">
    <tr>
    <td>
    <xsl:value-of select="@name" />
    </td>
    </tr>
    </xsl:for-each>
    </xsl:template>
    <xsl:template name="printNotEmptyTarget">
    <xsl:for-each select="project/target[@depends!='']">
    <tr>
    <td>
    <xsl:value-of select="@name" />
    </td>
    <td>
    <xsl:value-of select="@depends" />
    <<<<<<<<<<<<< Start // This I have problem >>>>>>>>>>>>>>>>>>>>>>>>
    <xsl:variable name="targetName" select="@name = @depends">
    <xsl:value-of select="$targetName" />
    <<<<<<<<<<<<< End // This I have problem >>>>>>>>>>>>>>>>>>>>>>>>
    </xsl:variable>
    </td>
    </tr>
    </xsl:for-each>
    </xsl:template>
    Edited by: Sun_day on Sep 14, 2007 1:48 AM

    shree wrote:
    1.Can you differentiate these XSLT, XPath and XQuery.XSL stands for EXtensible Stylesheet Language, and is a style sheet language for XML documents. XSLT stands for XSL Transformations.
    XQuery is to XML what SQL is to database tables. XQuery was designed to query XML data.
    XPath is used to navigate through elements and attributes in an XML document. XPath is a major element in W3C's XSLT standard - and XQuery and XPointer are both built on XPath expressions.
    http://www.w3schools.com/xsl/default.asp
    http://www.w3schools.com/xquery/default.asp
    http://www.w3schools.com/xpath/default.asp
    Cheers,
    Vlad

  • Recursively Finding a Node in a Linked List

    I'm trying to find a node recursively in this linked list but keep coming up with an error message - can anyone tell me what is wrong?
         public boolean find (Object obj)
              DonorNode node = new DonorNode(obj);
              DonorNode current = list;
              if (don.equals(current))
                   return true;
              else
                   return find(current.next);
         }

    Please post within code tags (button above the message box).
    Without more information it's hard to say.
    What is list?
    What is don?
    If you don't mind me pointing out:
    A method named find conventionally returns some object it is searching for or null if not found.
    What you have (by that I mean a method returning boolean) is generally named contains (or some other obvious predicate name).
    That being said, if I assume that DonorNodes contain some Object and have getter functions to access those; and that list is a DonorNode representing the head of the list, try something like:public boolean contains(Object o) {
        return contains(o, list);
    private boolean contains(Object o, DonorNode n) {
        if (n.getObject() == o)
            return true;
        if (n.getNext() == null)
            return false;
        return contains(o, n.getNext());
    }Although keep in mind that comparing two Objects using '==' will result in reference only comparison. If you need some other form of comparison you might consider using the equals method (make sure you then implement it in all potentially contained classes) or even narrowing the accepted argument to classes that implement the Comparable interface.
    Hope this helps.

  • XSLT recursion changed direction from JDK1.4 to JDK1.5?

    We make use of XSLT template recursion, and when we tried to test our code with JDK 1.5, the recursion "changed direction". I believe some sort of optimization is taking place that's inappropriately switching around the order or something.
    Here's a test case:
    test-data.xml:
    <?xml version="1.0" encoding="utf-8"?>
    <rating>3</rating>test-temp.xml:
    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet
        version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html"/>
    <xsl:template match="/">
    <html>
    <body>
    <xsl:call-template name="showRating">
    <xsl:with-param name="num" select="'1'"/>
    </xsl:call-template>
    </body>
    </html>
    </xsl:template>
    <!-- SHOW RATED STARS -->
    <xsl:template name="showRating">
       <xsl:param name="num"/>
        <xsl:if test="$num <= rating">
        <img border="0" src="yellow_star.gif" valign="absmiddle"/>
        </xsl:if>
        <xsl:if test="$num > rating">
        <img border="0" src="white_star.gif" valign="absmiddle"/>
        </xsl:if>
    <xsl:if test="$num <= '4'">
    <xsl:text>
    </xsl:text>  <!-- CRLF -->
    <xsl:call-template name="showRating">
    <xsl:with-param name="num" select="$num + 1" />
    </xsl:call-template>
    </xsl:if>
    </xsl:template>
    </xsl:stylesheet>testxslt.java:
    import java.io.*;
    import javax.xml.transform.*;
    import javax.xml.transform.stream.*;
    public class testxslt {
      public static void main(String[] args) {
        try {
          new testxslt();
        catch(Throwable t) {
          System.err.println(t + ": " + t.getMessage());
          t.printStackTrace();
      private testxslt() throws Exception {
        String stylesheet = readFile("test-temp.xml");
        String data = readFile("test-data.xml");
        String out = transform(stylesheet, data);
        System.out.println(out);
      private String readFile(String filename) throws IOException {
        StringBuffer out = new StringBuffer();
        Reader r = new FileReader(filename);
        int count;
        char buf[] = new char[1024];
        while((count = r.read(buf)) > 0)
          out.append(buf, 0, count);
        r.close();
        return out.toString();
      private String transform(String stylesheet, String data) throws Exception {
        ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
        StreamResult transStreamResult = new StreamResult(resultStream);
        Source xmlData = new StreamSource(new StringReader(data));
        StreamSource styleSource = new StreamSource(new StringReader(stylesheet));
        TransformerFactory tf = TransformerFactory.newInstance();
        Templates t = tf.newTemplates(styleSource);
        Transformer trans = t.newTransformer();
        trans.transform(xmlData, transStreamResult);
        return resultStream.toString();
    }If you run it with jdk1.4, the yellow stars will (correctly) print first. If you run it with JDK 1.5, the white stars will print first.
    WTF?

    More info: I downloaded xalan from xml.apache.org, and by adding xalan.jar to the classpath, I can get JDK1.5 to output the stars in the right order. So this appears to be some issue having directly to do with the XSLTC transformer.

  • How do i expand all the nodes in a jtree

    Hi,
    I am working on a project where i need to expand all the nodes of a jtree i have tried a few different ways but it never seems to expand all the nodes..
    I would be very greatful if someone could point me in the right direction
    cheers
    Mary

    you could use the following method that expands nodes recursively
    expandNode( myTree, myRootNode, new TreePath( myRootNode ) );
    public static void expandNode( JTree tree, TreeNode node, TreePath path ) {
        tree.expandPath( path );
        int i = node.getChildCount( );
        for ( int j = 0; j< i; j++ ) {
            TreeNode child = node.getChildAt( j );
            expandNode( tree, child , path.pathByAddingChild( child ) );
    }

  • Recursing through table / complex return types in Java Stored Functions

    I have a table representing a tree with arbitrary depth, of the form:
    ID NUMBER(10) PRIMARY KEY,
    NAME VARCHAR2(20),
    PARENT NUMBER(10)
    with PARENT being a foreign key for ID, so that top-level nodes in the tree have a NULL PARENT, and other nodes have the ID of their parent node in the PARENT field.
    I want a good way to get a row representing a node as well as all its ancestor nodes recursively up to the top level. I do this a lot in my Java application, and right now it works by just getting each row, checking if PARENT is null, and recursing again until I get the top-level node. Since this recursion is in Java and I do multiple queries it's rather slow, and I'd rather perform this operation in the database (using a Java Stored Function/Procedure or PL/SQL).
    I'm no good at PL/SQL so don't have a clue how to go about doing this sort of thing, and although I can write a Java Stored Function that does the same recursion I do in the application, I don't know how to return the results. I can't return a REF CURSOR type since the results are from multiple queries, and I can't find any documentation about how to return structured types from a JSF.
    If anyone could give me a near-complete PL/SQL listing that does this or (better) help me to complete my Java Stored Function by returning the results in a structured type.

    You are my own personal God (for the day). Thanks, exactly what I needed, and all in one query with no procedural.

  • Collection to represent ol ul il structures in recursive function

    Hello
    Im trying to write a terminal based web-browser and have a little problem when it comes to presentation of <ul><ol><li> tags.
    Im using recursion to step through the tags and the main function looks something like this (just wrote down a simplified version) It reads an xhtml document.
    private boolean  inBody= false;
    private int numberOfB = 0;
    private int numberOfEm = 0;
    public void printNodeLeaves(Node N)
         switch (N.getNodeType())
    case Node.DOCUMENT_NODE:
    case Node.ELEMENT_NODE:
    String nName = N.getNodeName(); //F�r ut taggar som B,P,EM osv
    if (nName.equalsIgnoreCase("body")) inBody= true;
    if (nName.equalsIgnoreCase("b")){
      numberOfB++;
      //Print out boldtext
    if (nName.equalsIgnoreCase("p")) itw.newline(2);
    if (nName.equalsIgnoreCase("em")){
         numberOfEm++;          
         //Print out italic text                    
    //Recursion      
    NodeList children= N.getChildNodes();
    if (children != null)
        for (int i=0; i<children.getLength(); ++i){              
             printNodeLeaves(children.item(i));              
    if (nName.equalsIgnoreCase("b")){
         numberOfB--;
         if(numberOfB==0) // Turn of the bold
         if(numberOfEm>0) // Turn on the italic
    if (nName.equalsIgnoreCase("em")) {
         numberOfEm--;
         if(numberOfEm==0) //Turn of the italic
         if(numberOfB>0) //Turn on bold
    if (nName.equalsIgnoreCase("p")) itw.newline(2);
         break;
         case Node.TEXT_NODE:
         if (inBody){                   
             itw.print(N.getNodeValue().replaceAll("\n", " "));                    
    }My problem is when it comes to the lists, both <ul> and <ol> tags contains <il>, im looking for a way to represent
    the lists in some kind of collection, linkedlist maybe. I was thinking of making a class that contains a list and property that tells me if the list is a <ul> or <ol>. The problem is that a <ul> could containt a <ol> and vice verca, ant of course they must be able to be nested. Why i need the ul and the ol in the same collection is because <il> in a <ol> should be outprinted with the number first followed by a dott, and <ul> should have a * in front of each <il>.
    Anyone that have any thoughts on this?

    Odd question. Why do you need to represent them in a collection? Seems like they're probably as well organized as they will be in the DOM. You should just process nodes recursively and if the current node is a "ol" then each child should be displayed with an integer that counts up from 1. If you hit an "ul" while processing the "ol" it shouldn't matter, you should process it then continue processing the "ol".
    One suggestion:
    use:
    String nName = N.getNodeName().toLowerCase().intern();
    then do if(nName == "tagname")
    as is, you are converting each character to lower case and comparing everytime. If you internalize, then == will work and is a simple reference comparison.
    More about internalization:
    http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#19369

  • Post Back Tree view when tree node check changed

    Hi everyone, 
    I have a tree view, both child and parent have check box. I want to check all the child on the parent selection. 
    I try "SelectedNodeChanged" but the page doesn't post back to fire my function.
    I know I can use javascript to post back the page, but is there any other way to post back my page without javascript???  
    Thnaks in advance. 

    Hi everyone, 
    I have a tree view, both child and parent have check box. I want to check all the child on the parent selection. 
    I try "SelectedNodeChanged" but the page doesn't post back to fire my function.
    I know I can use javascript to post back the page, but is there any other way to post back my page without javascript???  
    Thnaks in advance. 
    Assuming this is a WinForm application (it looks like it may not be), the following works pretty well:
    Option Strict On
    Option Explicit On
    Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
    Handles MyBase.Load
    With TreeView1
    .CheckBoxes = True
    .ShowLines = True
    .ShowPlusMinus = True
    .ShowRootLines = True
    .ExpandAll()
    End With
    End Sub
    ' Updates all child tree nodes recursively.
    Private Sub CheckAllChildNodes(ByVal treeNode As TreeNode, ByVal nodeChecked As Boolean)
    Dim node As TreeNode
    For Each node In treeNode.Nodes
    node.Checked = nodeChecked
    If node.Nodes.Count > 0 Then
    ' If the current node has child nodes, call the CheckAllChildsNodes method recursively.
    Me.CheckAllChildNodes(node, nodeChecked)
    End If
    Next node
    End Sub
    ' NOTE This code can be added to the BeforeCheck event handler instead of the AfterCheck event.
    ' After a tree node's Checked property is changed, all its child nodes are updated to the same value.
    Private Sub node_AfterCheck(ByVal sender As Object, ByVal e As TreeViewEventArgs) Handles TreeView1.AfterCheck
    ' The code only executes if the user caused the checked state to change.
    If e.Action <> TreeViewAction.Unknown Then
    If e.Node.Nodes.Count > 0 Then
    ' Calls the CheckAllChildNodes method, passing in the current
    ' Checked value of the TreeNode whose checked state changed.
    Me.CheckAllChildNodes(e.Node, e.Node.Checked)
    End If
    End If
    End Sub
    End Class
    The reference for that is this MSDN document.
    If you're looking for a true tri-state operation though, honestly you might want to look at some third-party controls.
    I hope that helps. :)
    Please call me Frank :)

  • Create a text file in KM and add the structure of a node

    Hello Everybody,
    could some one please advise on how do I write the data stored in my node (elements) as string into a text file? How can i create a text file and add the structure of my node to it? I can just walk through my node recursively.
    Any help would be highly appreciated.
    Thanks in advance.
    Regards,
    Seed

    Are you referring to a org.w3c.dom.Node?
    In that case, the simplest approach would be to use KM's XML serializer (http://help.sap.com/javadocs/NW04s/current/km/com/sapportals/wcm/util/xml/SimpleSerializer.html)
    BR, Julian

  • How to recursivly search and replace nodes in a document

    Hi,
    i am trying to go through a document that i ahve parsed, and search for and replace specific node values. I am putting the root node in as the element to start searching from.
    My code is below, can somone please point out where i am going wrong?
      //Sets the existing text node with the new value as selected by the user
         public static void setTextNode(Element e, String aTagName, String aTagValue, Document doc)
               NodeList children = e.getChildNodes();
               //Loop through all the outer elements
               for (int i=0; i<children.getLength(); i++)
                    Node childNode = children.item(i);
                    if (childNode instanceof Element)
                         Element childElement = (Element)childNode;
                         //Loop through all the children of this element to check for the tag we are looking for
                         NodeList childElementChildren = childElement.getChildNodes();
                              for (int j=0; j < childElementChildren.getLength(); j++)
                                   Node chNode = childElementChildren.item(j);
                                        try
                                             Element elem = (Element)chNode;
                                            if (elem.getChildNodes().getLength()> 1)     
                                                 setTextNode(elem, aTagName, aTagValue,doc);
                                            else
                                                 if (elem.getTagName().equals(aTagName))                         
                                                      Node node = childElement.getFirstChild();
                                                      node.setNodeValue(aTagValue);
                                        catch (Exception io)
                                             io.printStackTrace();
                              }

    Yes, this replaces your code. If you look at the example I posted before you can see that it replaces existing text values with the new value. The only thing it doesn't do is add the text to tags that don't have an existing text node. So
    <NodeA><NodeB>stuff</NodeB><NodeB></NodeB></NodeA>with "aTagName=NodeB" and "aTagValue=newVal" comes back as
    <NodeA><NodeB>newVal</NodeB><NodeB></NodeB></NodeA>Notice, the second NodeB did not have the value added. If you want it to add a text node if there isn't one so it comes back as
    <NodeA><NodeB>newVal</NodeB><NodeB>newVal</NodeB></NodeA>then make it look like this:
        public static void setTextNode(Node node, String aTagName, String aTagValue)
            if(node.getNodeType() == Node.ELEMENT_NODE)
                NodeList children = node.getChildNodes();
                int numChildren = children.getLength();
                if(numChildren == 0)
                    if(node.getNodeName().equals(aTagName))
                        // If there aren't any children but the tag is what we are looking for
                        // add a new text node with the passed value.
                        Document doc = node.getOwnerDocument();
                        Text txtNode = doc.createTextNode(aTagValue);
                        node.appendChild(txtNode);
                else
                    // If there are children loop through them
                    for(int i=0; i<numChildren; i++)
                        Node child = children.item(i);
                        short type = child.getNodeType();
                        if(type == Node.ELEMENT_NODE)
                            // If its an element node, recursively call our method to keep looking
                            setTextNode(child, aTagName, aTagValue);
                        else if(type == Node.TEXT_NODE && node.getNodeName().equals(aTagName))
                            // Change the value of this node's text-type child node
                            child.setNodeValue(aTagValue);
        }Just replace your method with this and give it a shot. If you have a Document you can call it like this:
    setTextNode(document.getFirstChild(), tagName, tagValue);If you try it and still don't understand, let me know and I'll try to help you integrate it in your code.
    -Paco

  • Difference between modal node and data node

    Hi Experts,
    One small basic question: What is the difference between a modal node and a data node?? Why do we bind a modal node with a function module and nota a data node?? Moreover, what is a recursion node n how cani make use of this node??
    Regards,
    KM

    Hi Kaustubh,
    Please check below documents:-
    Thread - [Value Node vs Model Node - 1|Value Node vs Model Node;
    Thread - [Value Node vs Model Node - 2|Value Note Vs Model Node;
    SAP Wikki - [Value Nodes,Model Nodes,Recursive Nodes |http://wiki.sdn.sap.com/wiki/display/WDJava/ValueNodes,ModelNodes,Recursive+Nodes]
    Hope it helps
    Regards
    Arun

  • How to hide elements from xml file when dumping to JTree?

    Hi everybody,
    I got a XML file similar to this one:
    <Dios>
    <Adan>
    <Hijos>
    <Vivos>
    <Nombre>Isaac</Nombre>
    <ColorOjos>Verdes</ColorOjos>
    <ColorPelo>Casta�o</ColorPelo>
    <Nombre>Paris</Nombre>
    <ColorOjos>Verdes</ColorOjos>
    <ColorPelo>Casta�o</ColorPelo>
    </Vivos>
    </Hijos>
    </Adan>
    <Eva>
    <Hijos>
    <Vivos>
    <Nombre>Jose</Nombre>
    <ColorOjos>Azules</ColorOjos>
    <ColorPelo>Rubio</ColorPelo>
    <Nombre>Marta</Nombre>
    <ColorOjos>Oscuros</ColorOjos>
    <ColorPelo>Casta�o</ColorPelo>
    </Vivos>
    <Fallecidos>
    <Nombre>Miriam</Nombre>
    <ColorOjos>Verdes</ColorOjos>
    <ColorPelo>Casta�o</ColorPelo>
    <Nombre>Dorian</Nombre>
    <ColorOjos>Azules</ColorOjos>
    <ColorPelo>Casta�o</ColorPelo>
    </Fallecidos>
    </Hijos>
    </Eva>
    </Dios>
    I must:
    1)Show datas on a Tree, with the exception that "ColorPelo" and "ColorOjos" values should not be displayed on the tree.
    2)When clicking over one leaf (for example: Miriam) on the right side of panel, should write the values of "ColorPelo" and "ColorOjos", verdes and casta�o.
    Don�t know where start. Any idea will be welcome
    Thanks in advance

    Sorry, the xml above was wrong, this is right xml:
    <Dios>
         <Adan>
              <Hijos>
                   <Vivos>
                        <Nombre>Isaac</Nombre>
                        <Caracteristicas>
                                  <ColorOjos>Verdes</ColorOjos>
                                  <ColorPelo>Casta�o</ColorPelo>
                        </Caracteristicas>
                        <Nombre>Paris</Nombre>
                        <Caracteristicas>
                                  <ColorOjos>Verdes</ColorOjos>
                                  <ColorPelo>Casta�o</ColorPelo>
                        </Caracteristicas>
                   </Vivos>
              </Hijos>
         </Adan>
         <Eva>
              <Hijos>
                   <Vivos>
                        <Nombre>Jose</Nombre>
                        <Caracteristicas>
                                  <ColorOjos>Azules</ColorOjos>
                                  <ColorPelo>Rubio</ColorPelo>
                        </Caracteristicas>
                        <Nombre>Marta</Nombre>
                        <Caracteristicas>
                                  <ColorOjos>Oscuros</ColorOjos>
                                  <ColorPelo>Casta�o</ColorPelo>
                        </Caracteristicas>
                   </Vivos>
                   <Fallecidos>
                        <Nombre>Miriam</Nombre>
                        <Caracteristicas>
                             <ColorOjos>Verdes</ColorOjos>
                             <ColorPelo>Casta�o</ColorPelo>
                        </Caracteristicas>
                        <Nombre>Dorian</Nombre>
                        <Caracteristicas>
                             <ColorOjos>Azules</ColorOjos>
                             <ColorPelo>Casta�o</ColorPelo>
                        </Caracteristicas>
                   </Fallecidos>
              </Hijos>Finally I know how to do first point, when creating the nodes(recursively):
    if( (children != null )&& *!root.getNodeName().equals("Caracteristicas")*)
    numChildren = children.getLength();
         for (int i=0; i < numChildren; i++)
         node = children.item(i);
         if( node != null && *!node.getNodeName().equals("Caracteristicas")*)
    ...

  • How can i write also to xml file the settings of the Tag property to identify if it's "file" or "directory" ?

    The first thing i'm doing is to get from my ftp server all the ftp content information and i tag it so i can identify later if it's a file or a directory:
    private int total_dirs;
    private int searched_until_now_dirs;
    private int max_percentage;
    private TreeNode directories_real_time;
    private string SummaryText;
    private TreeNode CreateDirectoryNode(string path, string name , int recursive_levl )
    var directoryNode = new TreeNode(name);
    var directoryListing = GetDirectoryListing(path);
    var directories = directoryListing.Where(d => d.IsDirectory);
    var files = directoryListing.Where(d => !d.IsDirectory);
    total_dirs += directories.Count<FTPListDetail>();
    searched_until_now_dirs++;
    int percentage = 0;
    foreach (var dir in directories)
    directoryNode.Nodes.Add(CreateDirectoryNode(dir.FullPath, dir.Name, recursive_levl+1));
    if (recursive_levl == 1)
    TreeNode temp_tn = (TreeNode)directoryNode.Clone();
    this.BeginInvoke(new MethodInvoker( delegate
    UpdateList(temp_tn);
    percentage = (searched_until_now_dirs * 100) / total_dirs;
    if (percentage > max_percentage)
    SummaryText = String.Format("Searched dirs {0} / Total dirs {1}", searched_until_now_dirs, total_dirs);
    max_percentage = percentage;
    backgroundWorker1.ReportProgress(percentage, SummaryText);
    percentage = (searched_until_now_dirs * 100) / total_dirs;
    if (percentage > max_percentage)
    SummaryText = String.Format("Searched dirs {0} / Total dirs {1}", searched_until_now_dirs, total_dirs);
    max_percentage = percentage;
    backgroundWorker1.ReportProgress(percentage, SummaryText);
    foreach (var file in files)
    TreeNode file_tree_node = new TreeNode(file.Name);
    file_tree_node.Tag = "file";
    directoryNode.Nodes.Add(file_tree_node);
    numberOfFiles.Add(file.FullPath);
    return directoryNode;
    The line i'm using to Tag is:
    file_tree_node.Tag = "file";
    So i know what is "file" then i make a simple check if the Tag is not null then i know it's a "file" if it's null then it's directory.
    For example this is how i'm checking if it's file or directory after getting all the content from my ftp server:
    if (treeViewMS1.SelectedNode.Tag != null)
    string s = (string)treeViewMS1.SelectedNode.Tag;
    if (s == "file")
    file = false;
    DeleteFile(treeViewMS1.SelectedNode.FullPath, file);
    else
    RemoveDirectoriesRecursive(treeViewMS1.SelectedNode, treeViewMS1.SelectedNode.FullPath);
    I also update in real time when getting the content of the ftp server xml file on my hard disk with the treeView structure information so when i'm running the program each time it will load the treeView structure with all directories and files.
    This is the class of the xml file:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml;
    using System.Windows.Forms;
    namespace FTP_ProgressBar
    class TreeViewXmlPopulation
    // Xml tag for node, e.g. 'node' in case of <node></node>
    private const string XmlNodeTag = "node";
    // Xml attributes for node e.g. <node text="Asia" tag=""
    // imageindex="1"></node>
    private const string XmlNodeTextAtt = "text";
    private const string XmlNodeTagAtt = "tag";
    private const string XmlNodeImageIndexAtt = "imageindex";
    public static void DeserializeTreeView(TreeView treeView, string fileName)
    XmlTextReader reader = null;
    try
    // disabling re-drawing of treeview till all nodes are added
    treeView.BeginUpdate();
    reader = new XmlTextReader(fileName);
    TreeNode parentNode = null;
    while (reader.Read())
    if (reader.NodeType == XmlNodeType.Element)
    if (reader.Name == XmlNodeTag)
    TreeNode newNode = new TreeNode();
    bool isEmptyElement = reader.IsEmptyElement;
    // loading node attributes
    int attributeCount = reader.AttributeCount;
    if (attributeCount > 0)
    for (int i = 0; i < attributeCount; i++)
    reader.MoveToAttribute(i);
    SetAttributeValue(newNode,
    reader.Name, reader.Value);
    // add new node to Parent Node or TreeView
    if (parentNode != null)
    parentNode.Nodes.Add(newNode);
    else
    treeView.Nodes.Add(newNode);
    // making current node 'ParentNode' if its not empty
    if (!isEmptyElement)
    parentNode = newNode;
    // moving up to in TreeView if end tag is encountered
    else if (reader.NodeType == XmlNodeType.EndElement)
    if (reader.Name == XmlNodeTag)
    parentNode = parentNode.Parent;
    else if (reader.NodeType == XmlNodeType.XmlDeclaration)
    //Ignore Xml Declaration
    else if (reader.NodeType == XmlNodeType.None)
    return;
    else if (reader.NodeType == XmlNodeType.Text)
    parentNode.Nodes.Add(reader.Value);
    finally
    // enabling redrawing of treeview after all nodes are added
    treeView.EndUpdate();
    reader.Close();
    /// <span class="code-SummaryComment"><summary>
    /// Used by Deserialize method for setting properties of
    /// TreeNode from xml node attributes
    /// <span class="code-SummaryComment"></summary>
    private static void SetAttributeValue(TreeNode node,
    string propertyName, string value)
    if (propertyName == XmlNodeTextAtt)
    node.Text = value;
    else if (propertyName == XmlNodeImageIndexAtt)
    node.ImageIndex = int.Parse(value);
    else if (propertyName == XmlNodeTagAtt)
    node.Tag = value;
    public static void SerializeTreeView(TreeView treeView, string fileName)
    XmlTextWriter textWriter = new XmlTextWriter(fileName,
    System.Text.Encoding.ASCII);
    // writing the xml declaration tag
    textWriter.WriteStartDocument();
    //textWriter.WriteRaw("\r\n");
    // writing the main tag that encloses all node tags
    textWriter.WriteStartElement("TreeView");
    // save the nodes, recursive method
    SaveNodes(treeView.Nodes, textWriter);
    textWriter.WriteEndElement();
    textWriter.Close();
    private static void SaveNodes(TreeNodeCollection nodesCollection,
    XmlTextWriter textWriter)
    for (int i = 0; i < nodesCollection.Count; i++)
    TreeNode node = nodesCollection[i];
    textWriter.WriteStartElement(XmlNodeTag);
    textWriter.WriteAttributeString(XmlNodeTextAtt,
    node.Text);
    textWriter.WriteAttributeString(
    XmlNodeImageIndexAtt, node.ImageIndex.ToString());
    if (node.Tag != null)
    textWriter.WriteAttributeString(XmlNodeTagAtt,
    node.Tag.ToString());
    // add other node properties to serialize here
    if (node.Nodes.Count > 0)
    SaveNodes(node.Nodes, textWriter);
    textWriter.WriteEndElement();
    And this is how i'm using the class this method i'm calling it inside the CreateDirectoryNode and i'm updating the treeView in real time when getting the ftp content from the server i build the treeView structure in real time.
    DateTime last_update;
    private void UpdateList(TreeNode tn_rt)
    TimeSpan ts = DateTime.Now - last_update;
    if (ts.TotalMilliseconds > 200)
    last_update = DateTime.Now;
    treeViewMS1.BeginUpdate();
    treeViewMS1.Nodes.Clear();
    treeViewMS1.Nodes.Add(tn_rt);
    TreeViewXmlPopulation.SerializeTreeView(treeViewMS1, @"c:\XmlFile\Original.xml");
    ExpandToLevel(treeViewMS1.Nodes, 1);
    treeViewMS1.EndUpdate();
    And when i'm running the program again in the constructor i'm doing:
    if (File.Exists(@"c:\XmlFile\Original.xml"))
    TreeViewXmlPopulation.DeserializeTreeView(treeViewMS1, @"c:\XmlFile\Original.xml");
    My question is how can i update the xml file in real time like i'm doing now but also with the Tag property so next time i will run the program and will not get the content from the ftp i will know in the treeView what is file and what is directory.
    The problem is that now if i will run the program the Tag property is null. I must get the ftp content from the server each time.
    But i want that withoutout getting the ftp content from server to Tag each file as file in the treeView structure.
    So what i need is somehow where i;m Tagging "file" or maybe when updating the treeView also to add something to the xml file so when i will run the progrma again and read back the xml file it will also Tag the files in the treeView.

    Hi
    Chocolade1972,
    Your case related to Winform Data Controls, So i will move your thread to Windows Forms> Windows
    Forms Data Controls and Databinding  forum for better support.
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

Maybe you are looking for