XML Parsing using a schema in C#

时间秒杀一切 提交于 2020-01-24 09:48:29

问题


I'm working on some code that loads an xml file at run time. At the minute, we're using the XmlDocument type to read the xml file and wrapping a try-catch around SelectSingleNode statement (this is done on the off chance that a node is null, or isn't there as we're parsing user created xml files).

Please note: I realise that XmlDocument has been replaced by XDocument. However since we're working with .NET version 3 (according to this MSDN document XDocument isn't available in .NET 3), we're having to stick with XmlDocument for now. We're using .NET 3 for a variety of reasons (some of which are spec related).

Here's an example of what we're doing at the minute:

private void LoadUserXMLFile ()
{
    XmlDocument xDoc = new XmlDocument();
    XmlTextReader reader = new XmlTextReader(fileName);
    reader.Read();
    xDoc.Load(reader);

    try { firstElementString = xDoc.SelectSingleNode(<path to node>).InnderText);
    catch { <exception handling here > }
    //more SelectSingleNode statements, each wrapped inside
    //individual try-catch blocks
}

Obviously the above is an example, and I've simplified the catch statement.

I've written a schema for the user generated XML files that this app will work with, and I was wondering if I used the schema (in some way) during parsing of an XML document, would I still need to wrap each SelectSingleNode with try-catch statements?

Is it even possible to use the schema (in some way) during parsing to check the XML document has the correct format and all of the required elements?


回答1:


Yes you need to use a validating reader

You can use something like this

XmlTextReader r = new XmlTextReader("C:\\Xml\\MyXmlFile.xml");
v.ValidationType = ValidationType.Schema;

Obviously your xml will refer to the schema so thats how the reference to that is resolved (in the xml itself) like so

<Employee EmployeeId="12345566" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="Employee.xsd">
   <PersonName>Krystan</PersonName>
</Employee>

if you cannot change the xml you can use XmlReaderSettings like this

public void SomeMethod()
{
    XmlReaderSettings xmlsettings = new XmlReaderSettings();
    xmlsettings.Schemas.Add("http://www.company.com/blah", "blah.xsd");
    xmlsettings.ValidationType = ValidationType.Schema;
    xmlsettings.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);

    XmlReader reader= XmlReader.Create("somefile.xml", xmlsettings);

    while (reader.Read()) { }
}

public void ValidationHandler(object sender, ValidationEventArgs args)
    void booksSettingsValidationEventHandler(object sender, ValidationEventArgs e)
{
    if (e.Severity == XmlSeverityType.Warning)
    {
        Console.Write("WARNING: ");
        Console.WriteLine(e.Message);
    }
    else if (e.Severity == XmlSeverityType.Error)
    {
        Console.Write("ERROR: ");
        Console.WriteLine(e.Message);
    }
}

to answer your question if you have validated against a schema and are selecting nodes known to be there you can dispense with the per node exception handeling but obviously you should guard against an exception that may come about because of file load etc.



来源:https://stackoverflow.com/questions/9868669/xml-parsing-using-a-schema-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!