In the .aspx file:
<asp:Xml id="xml1" runat="server" />
In the .aspx.cs file:
XmlSchema schema = new XmlSchema();
XmlSchemaElement elementRoot = new XmlSchemaElement();
schema.Items.Add(elementRoot);
elementRoot.Name = "root";
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(schema);
settings.ValidationType = ValidationType.Schema;
settings.DtdProcessing = DtdProcessing.Prohibit; // to prevent XXE attack.
StringReader sr = new StringReader(xmlInString);
XmlReader reader = XmlReader.Create(sr, settings);
xml1.Document.XmlResolver = null; // to prevent XXE attack.
xml1.Document.Load(reader);
Note: the schema generated has only the root element (as below). If xmlInString contains any type of children elements, it will be validated as good.
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root"/>
</xs:schema>
Since Xml.Document is an obsolete property, for the above example, we should use another property DocumentContent. If Schema validation is not needed, we have a much simpler code:
xml1.DocumentContent = xmlInString;
Thursday, June 13, 2019
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment