Converting XML to DOT I would like to show an XML tree as a tree using GraphViz Dot tool. Then I must convert it to a DOT file. 

It is what I have tried

    string dot = "digraph G {" + Environment.NewLine;
    XML2DOT(XmlRoot, "r");
    dot += Environment.NewLine + "}";
    ....
    private void XML2DOT(XmlNode n, string id)
    {
        if (n == null)
            return;
        string NodeName = n.Name.Replace("-", "_");
        if (n.HasChildNodes)
        {
            dot += Environment.NewLine + NodeName 
                + id + "[label=\"" + NodeName + "\"];";
        }
        else
        {
            dot += Environment.NewLine 
                + "leaf" + id + "[label=\"" + n.InnerText + "\"];";
        }
        int i = 0;
        foreach (XmlNode item in n.ChildNodes)
        {
            string cid = id + i;
            dot += Environment.NewLine + NodeName + id + " -&gt; " 
            + (item.HasChildNodes ? item.Name.Replace("-", "_") : "leaf") 
            + cid + ";";
            XML2DOT(item, cid);
            i++;
        }
   }


The input xml is:

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;S&gt;
&lt;MN clitic="empty" ne_sort="pers"&gt;
   &lt;PUNC clitic="empty"&gt;
      &lt;w clitic="empty" gc="Ox" lc="Ox" lemma="#"&gt;#&lt;/w&gt;
   &lt;/PUNC&gt;
   &lt;MN clitic="empty" ne_sort="pers"&gt;
      &lt;N clitic="ezafe"&gt;
         &lt;w clitic="ezafe" gc="Apsz ; Nasp--- ; Nasp--z ; Ncsp--z" lc="Nasp--z" lemma="مسعود" n_type="prop" ne_sort="pers"&gt;مسعود&lt;/w&gt;
      &lt;/N&gt;
      &lt;N clitic="ezafe"&gt;
         &lt;w clitic="ezafe" gc="Apsy ; Nasp--- ; Nasp--z ; Ncsp--y" lc="Nasp--z" lemma="شجاعی" n_type="prop" ne_sort="pers"&gt;شجاعی&lt;/w&gt;
      &lt;/N&gt;
      &lt;N clitic="empty"&gt;
         &lt;w clitic="empty" gc="Nasp--- ; Nasp--z" lc="Nasp---" lemma="طباطبایی" n_type="prop" ne_sort="pers"&gt;طباطبایی&lt;/w&gt;
      &lt;/N&gt;
   &lt;/MN&gt;
   &lt;PUNC clitic="empty"&gt;
      &lt;w clitic="empty" gc="Ox" lc="Ox" lemma="#"&gt;#&lt;/w&gt;
   &lt;/PUNC&gt;
&lt;/MN&gt;
&lt;/S&gt;


And it is what I get:



It works as expected, just would like to know a more general and efficient way to do that.
There's an XML syntax for DOT called DotML at http://martin-loetzsch.de/DOTML/. Generating a generic DotML tree from XML is very straightforward using XSLT. Most of it is just:

&lt;xsl:template match="*"&gt;
  &lt;node id="{generate-id()}" label="{name()}"/&gt;
  &lt;edge from="{generate-id(..)}" to="{generate-id()}"/&gt;
  &lt;xsl:apply-templates/&gt;
&lt;/xsl:template&gt;

&lt;xsl:template match="text()"&gt;
  &lt;node id="{generate-id()}" label="{.}"/&gt;
  &lt;edge from="{generate-id(..)}" to="{generate-id()}"/&gt;
&lt;/xsl:template&gt;