[quoted text, click to view] "Robert Reineri" <robert123@reineri.org> wrote in message news:#hWVA3OREHA.132@TK2MSFTNGP09.phx.gbl...
> New to the XML world and .NET. I have what I believe to be a simple problem,
> but I have read the .NET docs till I'm blue in the face and still can't
> locate a simple example of how to accomplish this.
>
> I have two strings (C# string type).
The likely reason why you're having difficulty finding such an example
is because holding XML in a String is very inefficient. Your XML
probably comes from some other source that can be represented
in a Stream or Reader, why not use that?
: :
[quoted text, click to view] > handler to respond when something goes wrong, but the validating reader
> needs a text reader, which needs a string reader and so on.
Looks like you're already aware of the solution.
[quoted text, click to view] > I was hoping for something like:
>
> try
> {
> XmlDocument doc = new XmlDocument();
> doc.Load(string xml, string schema);
That would encourage inefficient programming practices. ;-)
Where there is support in the .NET Framework for parsing XML from
a UTF-16 String representation, the methods are conventionally named
with an -Xml ending (for example, ReadXml( ) or LoadXml( )). Here
the undecorated method name (Read( ) or Load( )) always operates
on Streams, Readers, or filename/URLs in a String.
Therefore, Load( string) always means a filename/URL, whereas
LoadXml( string) means the String contains UTF-16 encoded XML.
If you need a convenience method just to wrap the few lines of code
necessarily to extract the XML from the String, you can try this,
- - - ValidatingXmlLoader.cs
using System;
using System.IO;
using System.Xml;
public sealed class ValidatingXmlLoader
{
public static XmlDocument Load( string strXml, string strSchemaXml)
{
// Prepare the XmlSchema, Read() throws an XmlException for any XML
// errors present in the .XSD
XmlSchema schema = new XmlSchema( );
// No ValidationEventHandler necessary if you just want XmlException thrown
// on an XML error in the instance document, that's the default behavior.
schema.Read( new StringReader( strSchemaXml), null);
// Create the XmlValidatingReader for the instance document.
XmlValidatingReader reader = new XmlValidatingReader(
new XmlTextReader( new StringReader( strXml)));
// Prepare a DOM document to contain the validated instance document.
XmlDocument doc = new XmlDocument( );
// Load the DOM document; if the strXml is not valid an XmlException will
// be thrown and no document will be returned.
doc.Load( reader);
return doc;
}
}
- - -
In your desired example code, you'd use this sample class like this,
try
{
XmlDocument doc = ValidatingXmlLoader.Load( xml, schema);
}
catch
{
Debug.WriteLine( "The validation failed.");
}
Derek Harmon