Ask Your Question
3

How do I obtain a list of errors in XML using XElement in C#?

asked 2021-05-09 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-02-27 22:00:00 +0000

qstack gravatar image

You can use the XDocument.Validate method to validate an XML document against a given schema and obtain a list of errors. Here's an example:

XDocument doc = XDocument.Load("example.xml");
XmlSchemaSet schema = new XmlSchemaSet();
schema.Add(null, "schema.xsd"); // replace "schema.xsd" with your schema file name

List<string> errors = new List<string>();
doc.Validate(schema, (sender, e) =>
{
    errors.Add(e.Message);
});

// print the list of errors
foreach (string error in errors)
{
    Console.WriteLine(error);
}

In this example, the XDocument.Load method reads an XML file into an XDocument object. The XmlSchemaSet object contains the schema against which the XML document is validated. The Validate method validates the document and adds any validation errors to the errors list. Finally, the list of errors is printed to the console.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-05-09 11:00:00 +0000

Seen: 13 times

Last updated: Feb 27 '23