Validating XML with XSD

前端 未结 3 1267
自闭症患者
自闭症患者 2020-12-30 12:46

I\'m running into real difficulties validating XML with XSD. I should prefix all of this and state up front, I\'m new to XSD and validation, so I\'m not sure if it\'s a code

相关标签:
3条回答
  • 2020-12-30 12:55

    I don't want the user to submit XML that's not defined in the XSD.

    Why do you care? Your schema validates the XML nodes that are in your namespace. Your processing logic processes the XML nodes that are in your namespace. Nodes that aren't in your namespace aren't relevant to either your schema or your logic.

    If it's truly essential to restrict all nodes in the XML document to a specific namespace, you can accomplish that by extending the basic XmlReader validating logic found here.

        public static void Main()
        {
            const string myNamespaceURN = "urn:my-namespace";
    
            XmlSchemaSet sc = new XmlSchemaSet();
            sc.Add(myNamespaceURN, "mySchema.xsd");
    
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas = sc;
            settings.ValidationEventHandler += ValidationCallBack;
    
            XmlReader reader = XmlReader.Create("myDocument.xml", settings);
    
            while (reader.Read())
            {
                if ((reader.NodeType == XmlNodeType.Element ||
                     reader.NodeType == XmlNodeType.Attribute)
                    &&
                    reader.NamespaceURI != myNamespaceURN)
                {
                    LogError(reader.NamespaceURI + " is not a valid namespace.");
                }
            }
        }
    
        private static void ValidationCallBack(object sender, ValidationEventArgs e)
        {
            LogError(e.Message);
        }
    
        private static void LogError(string msg)
        {
            Console.WriteLine(msg);
        }
    
    0 讨论(0)
  • 2020-12-30 13:11

    Well, for one - your XSD defines a XML namespace xmlns="urn:bookstore-schema" which is not present in your XML test file - therefore, nothing in your XML test file will be validated.

    If you remove those elements form your schema:

    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <xsd:element name="title" type="xsd:string" />
    

    then it will properly validate your XML test file and complain about the wrong elements.

    Also using an element named <xml> might not be a great idea - since the directive <?xml ......?> is a pre-defined directive and should not appear as tag name elsewhere in your document.

    Marc

    0 讨论(0)
  • 2020-12-30 13:18

    You may also try XmlValidatingReader for XML validation

    0 讨论(0)
提交回复
热议问题