Click here to Skip to main content
15,915,093 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi..
i have used libxml2.Here when i am getting an XML data as a string i am unable to check whether it is a valid xml or a broken xml.so can anyone let me know how to check for the validation of xml in c using libxml2 or can suggest any more way to check for the validation.
Posted

I don't use libxml2 either but if you'd like to use Microsoft's MSXML4

#import <msxml4.dll>
using namespace MSXML2;

CString SchemaValidator::validateFile(CString file)
{
	// Initialize objects and variables.
	
	IXMLDOMDocument2Ptr pXMLDoc = NULL;
	MSXML2::IXMLDOMParseErrorPtr pError = NULL;
	_bstr_t strFile = (LPCTSTR)file;
	
	// Create a DOMDocument and set its properties.
	
	pXMLDoc.CreateInstance(__uuidof(DOMDocument40));
	pXMLDoc->async = VARIANT_FALSE;
	pXMLDoc->validateOnParse = VARIANT_TRUE;
	pXMLDoc->resolveExternals = VARIANT_TRUE;
	
	// Load and validate the specified file into the DOM.
	
	pXMLDoc->load(strFile);
	pError = pXMLDoc->parseError;
	
	// Return validation results
	
	if (pError->errorCode != S_OK)
	{
		CString res;
		res.Format("Reason: %s, Line: %d \"%s\"", (char *)pError->Getreason(), pError->Getline(), (char *)pError->GetsrcText());
		res.Replace("\r\n", "");
		return res;
	}
	else
		return CString();
}
</msxml4.dll>
 
Share this answer
 
Comments
Aescleal 15-Apr-12 2:44am    
MSXL4 can also be used in the same manner as expat - use it in SAX/event driven mode with all NULL handlers and let it fly. When it finishes you'll know if the XML is well formed or not.

This should (I don't know never having tested it) be faster and take less memory as it doesn't have to form the DOM tree.
I've not used libxml2 but if you get stuck and no one posts a better answer expat will do the job.

With expat you parse a buffer using XML_Parse and check the return code. If it returns an error (which it should for malformed XML) then call XML_GetErrorCode and (optionally) XML_Error which will tell you what went wrong. XML_GetCurrentLineNumber and XML_GetCurrentColumnNumber will tell you where it went wrong.

Sorry I can't be anymore help with libxml2 - I imagine it does somehow parse buffers, it'd be mad for it not to!

Cheers,

Ash
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900