tags:

views:

62

answers:

2

Is it possible for a .xsd file to also validate a .xml file by encoding type?

We have a system which can not read xml files starting like this:

<?xml version="1.0" encoding="utf-16" standalone="yes"?>

So I want to validate them before feeding them to that system and check if they start with

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
+1  A: 

No, XSD cannot do this. It is about validating the contents of an XML document, and the two XML documents are the same if they simply have different encodings.

Why not simply send them data with the correct encoding?

Hint: when you see UTF-16 coming from a .NET program, it's often because you've been writing your XML to a string, possibly through a StringWriter. Since strings in .NET are Unicode, this automatically makes the encoding UTF-16. I don't believe that can be changed, but if you don't output it to a string, then you don't have the problem.

John Saunders
A: 

In .NET you can check the XML declaration from the XmlDeclaration instance at the top of your XML document.

XmlTextReader reader = new XmlTextReader(@"C:\books.xml");

while (reader.Read())
{
    XmlNodeType type = reader.NodeType; 
    switch (type)
    {
        case XmlNodeType.XmlDeclaration:
             //do something with reader
             break;
    }
}
spoon16