Reputation: 53
I have an XML and XSD.
The problem I have is that if one element\attribute fails during the upload then nothing is uploaded. Therefore using the XSD, I would like to strip out any invalid “rows” prior to the upload.
If the following is taken as example
<Row>
<Column1>1</Column1>
<Column2>2</Column2>
</Row>
<Row>
<Column1>1</Column1>
<Column2>2</Column2>
</Row>
<Row>
<Column1>1</Column1>
**<Column2>**B**</Column2>**
</Row>
<Row>
<Column1>1</Column1>
**<Column2>**C**</Column2>**
</Row>
In the above example, Column2 in the 3rd Row and 4th row is invalid. Therefore I would like to remove it both from the XML.
I tried
foreach (XmlElement row in doc.SelectNodes("TableName/Row"))
{
if (row.SchemaInfo.Validity == XmlSchemaValidity.Invalid)
{
row.ParentNode.RemoveChild(row);
}
}
but it removes only the first error section and if later there are sections with error the SchemaInfo.Validity value is "NotKnown"
Upvotes: 0
Views: 420
Reputation: 6003
I think the only way to do this would be to manually validate the XML using your own code.
Due to the possible structure of an XSD and the possible errors that could occur in it, creating a validator that can consistently skip over an error and continue, would be very difficult (and hence is not something that any of the parsers i'm aware of have done).
In some circumstances they will continue validation after an error, but typically they then ignore all siblings after the initial error (in order to get back to a more consistent state). Basically once an error is encountered there are often multiple validation paths that can be taken as the validation state has become ambiguous.
That said if your data is something along the lines of your sample and you have some control over your XSD you could refactor the XSD defintion of <row> to be root element (then use an element ref where you need it). You could then load each <row> element one at a time and validate each one as you go. That way the code that reads the document is disconnected from the validation of each <row>, so if one is invalid you discard it and move onto the next.
NOTE : This approach would mean the rest of the XML document is NOT validated.
Upvotes: 1