-1

I have an xml file that refers to a local dtd file. But the problem is that my files are being compressed into a single file (I am using Unity3D and it puts all my textfiles into one binary). This question is not Unity3D specific, it is useful for anyone that tries to load a DTD schema from a string.

I have thought of a workaround to load the xml and load the dtd separately and then add the dtd file to the XmlSchemas of my document. Like so:

private void ReadConfig(string filePath)
{
    // load the xml file
    TextAsset text = (TextAsset)Resources.Load(filePath);
    StringReader sr = new StringReader(text.text);
    sr.Read(); // skip BOM, Unity3D catch!

    // load the dtd file
    TextAsset dtdAsset = (TextAsset)Resources.Load("Configs/condigDtd");

    XmlSchemaSet schemaSet = new XmlSchemaSet();
    schemaSet.Add(...); // my dtd should be added into this schemaset somehow, but it's only a string and not a filepath.

    XmlReaderSettings settings = new XmlReaderSettings() { ValidationType = ValidationType.DTD, ProhibitDtd = false, Schemas = schemaSet};
    XmlReader r = XmlReader.Create(sr, settings);

    XmlDocument doc = new XmlDocument();
    doc.Load(r);
}

The xml starts like this, but the dtd cannot be found. Not strange, because the xml file was loaded as a string, not from a file.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE Scene SYSTEM "configDtd.dtd">
Marnix
  • 6,384
  • 4
  • 43
  • 78

1 Answers1

2

XmlSchema has a Read method that takes in a Stream and a ValidationEventHandler. If the DTD is a string, you could convert it to a stream

System.Text.Encoding encode = System.Tet.Encoding.UTF8;
MemoryStream ms = new MemoryStream(encode.GetBytes(myDTD));

create the XmlSchema

XmlSchema mySchema = XmlSchema.Read(ms, DTDValidation);

add this schema to the XmlDocument containing the xml you are validating

myXMLDocument.Schemas.Add(mySchema);
myXMLDocument.Schemas.Compile();
myXMLDocument.Validate(DTDValidation);

The DTDValidation() handler would contain code handling what to do if the xml is invalid.

Anna Brenden
  • 3,837
  • 2
  • 21
  • 19
  • Thanks, it almost seemed to work. But Mono is throwing an xmlexception about declarations that could not be found. I think this would work if I would not be working in mono. So thumbs up for this one. I will try to use xsd files instead. – Marnix May 09 '12 at 11:35