XML Validation against schema not working c#

I am validating a xml string against a predefined schema as shown in the code. But the reader is only checking for the wellformedness but not the elements.

For example. if I pass a string link

<root>Hello</root>

the method should reject the string. But the code says the input xml is valid where it is not.

Am I missing something in it. I feel I should add a namespace somewhere.

Thanks.
internal static bool IsValid(string xml)
       {
           errorsExist = false;
           try
           {
               XmlSchemaSet schemaSet = new XmlSchemaSet();
               schemaSet.Add(null, new XmlTextReader(new StringReader(_schema.Trim()))); // _schema consists of the schema definition
               XmlReaderSettings settings = new XmlReaderSettings();
               settings.ValidationType = ValidationType.Schema;
               settings.Schemas = schemaSet;
               settings.ValidationEventHandler += new ValidationEventHandler(LogErrors);
               XmlReader reader = XmlReader.Create(new XmlTextReader(new StringReader(xml.Trim())), settings);
               while (reader.Read()) ;
           }
           catch (Exception e)
           {
               errorsExist = true;
           }
           return (!errorsExist);
       }
 
       private static void LogErrors(object sender, ValidationEventArgs args)
       {
           errorsExist = true;
       }
 
Schema I am using 
 
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Schema"
    targetNamespace="http://Schema.xsd"
    elementFormDefault="qualified"
    xmlns="http://Schema.xsd"
    xmlns:mstns="http://Schema.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
	<xs:element name="Employee">
		<xs:complexType>
			<xs:sequence>
				<xs:element name="Firstname" type="xs:string"></xs:element>
				<xs:element name="Lastname" type="xs:string"></xs:element>
			</xs:sequence>
		</xs:complexType>
	</xs:element>
 
</xs:schema>

Open in new window

VootanAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

VelioCommented:
the following input will return false:

<root xmlns=\"http://Schema.xsd\">Hello</root>
0
VelioCommented:
ignore the escaping backslashes :D
0
VootanAuthor Commented:
But we cannot enforce the user to enter the namespace in the xml, right?
Is there a way to validate the xml without that namespace?
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

VelioCommented:
unfortunately you have to reference the schema somewhere in the xml you're validating. one possible solution is to load the xml you're validating into a XmlDocument object, manually add the xmlns attribute to the DocumentElement and validate the xml document. I will try to give you a code sample.
0
VelioCommented:
Something like this.

I think this is rather crude but will work fine for xml documents that aren't too big.

if you can optimise it to use XmlDocument.Validate without having to save the modified xml, you might want to do that. it didn't quite work when i tried.

hope it helps.
        internal static bool IsValid(string xml)
        {
            errorsExist = false;
            try
            {                
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(new StringReader(xml.Trim()));
                if (xmlDocument.DocumentElement.Attributes.GetNamedItem("xmlns") == null)
                {
                    XmlAttribute attribute = xmlDocument.CreateAttribute("xmlns");
                    attribute.Value = "http://Schema.xsd";
                    xmlDocument.DocumentElement.Attributes.Append(attribute);
                }
                StringBuilder modifiedXml = new StringBuilder();
                xmlDocument.Save(new StringWriter(modifiedXml));
                xml = modifiedXml.ToString();
                XmlSchemaSet schemaSet = new XmlSchemaSet();
                schemaSet.Add(null, new XmlTextReader(new StringReader(_schema.Trim()))); // _schema consists of the schema definition
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.Schemas = schemaSet;
                settings.ValidationType = ValidationType.Schema;
                settings.ValidationEventHandler += new ValidationEventHandler(LogErrors);
                XmlReader reader = XmlReader.Create(new XmlTextReader(new StringReader(xml.Trim())), settings);
                while (reader.Read()) ;
 
            }
            catch (Exception e)
            {
                errorsExist = true;
            }
            return (!errorsExist);
        }
 
        private static void LogErrors(object sender, ValidationEventArgs args)
        {
            errorsExist = true;
        }

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
VelioCommented:
also, replace line 7 with

if (xmlDocument.DocumentElement.Attributes.GetNamedItem("xmlns") != "http://Schema.xsd")

this will make sure you validate against your schema regardless of whether there's another one in the xml.

i feel curiously dirty after all this, i'm sure there's a more "proper" way of doing this, so i hope solving your problem is a more important than elegance :)
0
VelioCommented:
i mean line 8.
0
VootanAuthor Commented:
I wonder if there is a more elegant way to do this.If yes, please let me know.
0
VootanAuthor Commented:
I wonder if there is a more elegant way to do this.If yes, please let me know
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.