Merge pull request #2800 from BrzVlad/feature-lazy-sweep
[mono.git] / mcs / tools / dtd2xsd / dtd2xsd.cs
1 using System;
2 using System.IO;
3 using System.Reflection;
4 using System.Xml;
5 using System.Xml.Schema;
6
7 using BF = System.Reflection.BindingFlags;
8
9 class Dtd2XsdDriver
10 {
11         public static void Main (string [] args)
12         {
13                 try {
14                         Run (args);
15                 } catch (Exception ex) {
16                         Console.WriteLine ("ERROR: " + ex.Message);
17                 }
18         }
19
20         static void Run (string [] args)
21         {
22                 if (args.Length < 1) {
23                         Console.WriteLine ("USAGE: mono dtd2xsd.exe instance-xmlfile [output-xsdfile]");
24                         return;
25                 }
26                 XmlTextReader xtr;
27                 if (args [0].EndsWith (".dtd"))
28                         xtr = new XmlTextReader ("<!DOCTYPE dummy SYSTEM '" + args [0] + "'><dummy/>",
29                                 XmlNodeType.Document, null);
30                 else
31                         xtr = new XmlTextReader (args [0]);
32                 XmlSchema xsd = Dtd2Xsd.Run (xtr);
33                 if (args.Length > 1)
34                         xsd.Write (new StreamWriter (args [1]));
35                 else
36                         xsd.Write (Console.Out);
37         }
38 }
39
40 public class Dtd2Xsd
41 {
42         public static XmlSchema Run (XmlTextReader xtr)
43         {
44                 while (xtr.NodeType != XmlNodeType.DocumentType) {
45                         if (!xtr.Read ())
46                                 throw new Exception ("DTD did not appeare.");
47                 }
48
49                 // Hacky reflection part
50                 object impl = xtr;
51                 BF flag = BF.NonPublic | BF.Instance;
52
53                 // In Mono NET_2_0 XmlTextReader is just a wrapper which 
54                 // does not contain DTD directly.
55                 FieldInfo fi = typeof (XmlTextReader).GetField ("source", flag);
56                 if (fi != null)
57                         impl = fi.GetValue (xtr);
58
59                 PropertyInfo pi = impl.GetType ().GetProperty ("DTD", flag);
60                 object dtd = pi.GetValue (impl, null);
61                 MethodInfo mi =
62                         dtd.GetType ().GetMethod ("CreateXsdSchema", flag);
63                 object o = mi.Invoke (dtd, null);
64                 return (XmlSchema) o;
65         }
66 }
67