Groups | Blog | Home
all groups > dotnet xml > march 2005 >

dotnet xml : REALLY CONFUSED: XmlValidatingReader and StringReader



Brian Pieslak
3/4/2005 11:34:00 AM
hi. I am trying to validate an XML against an XSD.
Both my XML and XSD are String variables inside of my method.
Here is my code:

....
xvr = New XmlValidatingReader( New XmlTextReader( New
StringReader(strXML) ) )
xvr.ValidationType = ValidationType.Schema
xvr.Schemas.Add( strTargetNamespace, New XmlTextReader( New StringReader(
strXSD ) ) )
AddHandler xvr.ValidationEventHandler, AddressOf ValidationHandler
Try
While xvr.Read()
End While
Catch ex As Exception
Debug.WriteLine(ex.Message)
Debug.WriteLine(ex.StackTrace)
End Try
....

And I receive the following execption:
The root element is missing.
at System.Xml.XmlTextReader.Read()
at System.Xml.XmlValidatingReader.ReadWithCollectTextToken()
at System.Xml.XmlValidatingReader.Read()

I know my XML & XSD are both well-formed documents.
In all of the other examples I have seen, others are successfully using the
MemoryStream to contain their XML & XSDs.
I have also seen StringReader->XmlTextReader->XmlValidatingReader questions
posted on newsgroups, but no one else seems to be running into my specific
exception.
I *could* go the route of creating MemoryStreams, but that seems like
overkill since I *should* be able to use the StringReader.

Has anyone seen this before?
Does anyone have the StringReader -> XmlTextReader -> XmlValidatingReader
working?
Thanks for the help,
Brian

Martin Honnen
3/4/2005 6:47:56 PM


[quoted text, click to view]


[quoted text, click to view]

Here is a simple C# example that works for me, it compiles and when run
it flags the validation error with the element content being the wrong type:

public static void Main (string[] args) {
const string xmlMarkup = @"<number
xmlns=""urn:example"">Kibo</number>";
const string xsdMarkup = @"<xs:schema
targetNamespace=""urn:example""
xmlns:xs=""http://www.w3.org/2001/XMLSchema""
elementFormDefault=""qualified"">
<xs:element name=""number"" type=""xs:double"" />
</xs:schema>";

XmlValidatingReader validator = new XmlValidatingReader(new
XmlTextReader(new StringReader(xmlMarkup)));
validator.ValidationEventHandler += new
ValidationEventHandler(ValidationHandler);
validator.Schemas.Add(@"urn:example", new XmlTextReader(new
StringReader(xsdMarkup)));

Console.WriteLine("Starting validation: ");
while (validator.Read()) {}
Console.WriteLine("Finished validation.");
}

public static void ValidationHandler (object sender,
ValidationEventArgs args) {
Console.WriteLine("{0}: {1}.", args.Severity, args.Message);
}



--

Martin Honnen
AddThis Social Bookmark Button