2010-04-15 Jb Evain <jbevain@novell.com>
[mcs.git] / tools / dtd2xsd / dtd2xsd.cs
blob3d53c54585f79c6889c5d6d7c01cc561a1a18ea0
1 using System;
2 using System.IO;
3 using System.Reflection;
4 using System.Xml;
5 using System.Xml.Schema;
7 using BF = System.Reflection.BindingFlags;
9 class Dtd2XsdDriver
11 public static void Main (string [] args)
13 try {
14 Run (args);
15 } catch (Exception ex) {
16 Console.WriteLine ("ERROR: " + ex.Message);
20 static void Run (string [] args)
22 if (args.Length < 1) {
23 Console.WriteLine ("USAGE: mono dtd2xsd.exe instance-xmlfile [output-xsdfile]");
24 return;
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);
40 public class Dtd2Xsd
42 public static XmlSchema Run (XmlTextReader xtr)
44 while (xtr.NodeType != XmlNodeType.DocumentType) {
45 if (!xtr.Read ())
46 throw new Exception ("DTD did not appeare.");
49 // Hacky reflection part
50 object impl = xtr;
51 BF flag = BF.NonPublic | BF.Instance;
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);
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;