问题
I am trying to validate an xml file via a .dtd. I have write this validator:
public bool Validation(XmlDocument xmlDoc)
{
var xml = XmldocToString(xmlDoc);
var r = new XmlTextReader(new StringReader(xml));
var settings = new XmlReaderSettings();
var sb = new StringBuilder();
settings.ProhibitDtd = false;
settings.ValidationType = ValidationType.DTD;
settings.ValidationEventHandler += (a, e) =>
{
sb.AppendLine(e.Message);
_isValid = false;
};
XmlReader validator = XmlReader.Create(r, settings);
while (validator.Read())
{
}
validator.Close();
return _isValid;
}
The problem is that I must have the dtd file in bin directory of the Solution. I want to chose a diferent directory to keep the .dtd file and i really can't find how.
Thank you for your time.
回答1:
Declare in the Xml file the association with the DTD:
Example in case the dtd is stored in a remote server:
<!DOCTYPE Catalog PUBLIC "abc/Catalog" "http://xyz.abc.org/dtds/catalog.dtd">
Take a look at that wiki page and at that site for more options and information about Xml files and DTD association.
Example in case the dtd is placed locally (SYSTEM):
How to reference a DTD from a document:
Assuming the top element of the document is spec and the dtd is placed in the file mydtd in the subdirectory dtds of the directory from where the document were loaded:
<!DOCTYPE spec SYSTEM "dtds/mydtd">
Notes:
The system string is actually an URI-Reference (as defined in RFC 2396) so you can use a full URL string indicating the location of your DTD on the Web. This is a really good thing to do if you want others to validate your document. It is also possible to associate a PUBLIC identifier (a magic string) so that the DTD is looked up in catalogs on the client side without having to locate it on the web. A DTD contains a set of element and attribute declarations, but they don't define what the root of the document should be. This is explicitly told to the parser/validator as the first element of the DOCTYPE declaration.
(Excerpt from here)
来源:https://stackoverflow.com/questions/13303672/validate-xml-via-dtd-different-directory-for-dtd