Wednesday, June 23, 2010

Read XML With Name Table Optimization

 protected ArrayList XmlReaderWithNTOptimization()
    {
        int bookCount = 0;
        decimal bookTotal =0;
        string Title = "";
        ArrayList arrList = new ArrayList();

        XmlReaderSettings settings = new XmlReaderSettings();
        NameTable nt = new NameTable();
        Object book = nt.Add("book");
        object price = nt.Add("price");
        object title = nt.Add("first-name");
        settings.NameTable = nt;

        string bookSchemaFile = Path.Combine(Request.PhysicalApplicationPath, "books.xsd");

        settings.Schemas.Add(null,XmlReader.Create(bookSchemaFile));
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;

        settings.ValidationEventHandler += new ValidationEventHandler(MyFunction);

        settings.IgnoreComments = true;
        settings.IgnoreWhitespace = true;


        string bookFile = Path.Combine(Request.PhysicalApplicationPath, "books.xml");

        using (XmlReader reader = XmlReader.Create(bookFile, settings))
        {

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && book.Equals(reader.LocalName))
                    bookCount++;
                if (reader.NodeType == XmlNodeType.Element && title.Equals(reader.LocalName))
                    arrList.Add(reader.ReadElementContentAsObject());
            }
        }

        Response.Write("found:    " + bookCount+"  Total Book Count: "+Title);
        return arrList;
    }

    protected void MyFunction(object sender, ValidationEventArgs e)
    {
        Response.Write(e.Message);
    }

No comments:

Post a Comment