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 + " -> "
+ (item.HasChildNodes ? item.Name.Replace("-", "_") : "leaf")
+ cid + ";";
XML2DOT(item, cid);
i++;
}
}
The input xml is:
<?xml version="1.0" encoding="UTF-8"?>
<S>
<MN clitic="empty" ne_sort="pers">
<PUNC clitic="empty">
<w clitic="empty" gc="Ox" lc="Ox" lemma="#">#</w>
</PUNC>
<MN clitic="empty" ne_sort="pers">
<N clitic="ezafe">
<w clitic="ezafe" gc="Apsz ; Nasp--- ; Nasp--z ; Ncsp--z" lc="Nasp--z" lemma="مسعود" n_type="prop" ne_sort="pers">مسعود</w>
</N>
<N clitic="ezafe">
<w clitic="ezafe" gc="Apsy ; Nasp--- ; Nasp--z ; Ncsp--y" lc="Nasp--z" lemma="شجاعی" n_type="prop" ne_sort="pers">شجاعی</w>
</N>
<N clitic="empty">
<w clitic="empty" gc="Nasp--- ; Nasp--z" lc="Nasp---" lemma="طباطبایی" n_type="prop" ne_sort="pers">طباطبایی</w>
</N>
</MN>
<PUNC clitic="empty">
<w clitic="empty" gc="Ox" lc="Ox" lemma="#">#</w>
</PUNC>
</MN>
</S>
And it is what I get:
It works as expected, just would like to know a more general and efficient way to do that.
