Tuesday, June 5, 2012

Best practices to parse xml files?


The default methods for dealing with xml in c# seem incredibly crude to me, leading me to suspect that I must be missing something in my searches. What is considered the standard best practices to parse xml files in c#?



Source: Tips4all

4 comments:

  1. I'd use LINQ to XML if you're in .NET 3.5.

    ReplyDelete
  2. it's very simple, I know this is standard methods but you can create your own library to deal with that much better.
    Here is some examples:

    XmlDocument xmlDoc= new XmlDocument(); //* create an xml document object.
    xmlDoc.Load("yourXMLFile.xml"); //* load the XML document from the specified file.

    //* Get elements.
    XmlNodeList girlAddress = xmlDoc.GetElementsByTagName("gAddress");
    XmlNodeList girlAge = xmlDoc.GetElementsByTagName("gAge");
    XmlNodeList girlCellPhoneNumber = xmlDoc.GetElementsByTagName("gPhone");

    //* Display the results.
    Console.WriteLine("Address: " + girlAddress[0].InnerText);
    Console.WriteLine("Age: " + girlAge[0].InnerText);
    Console.WriteLine("Phone Number: " + girlCellPhoneNumber[0].InnerText);


    Also there are some other methods to work with. f.ex here. And I think there are no one best method to do this, you always need to choose it by your self, what is most suitable for you.

    ReplyDelete
  3. Use a good XSD Schema to create a set of classes with xsd.exe and use an XmlSerializer to create a object tree out of your XML and vice versa. If you have few restrictions on your model, you could even try to create a direct mapping between you model classes and the XML with the Xml*Attributes.

    There is an introductory article about XML Serialisation on MSDN.

    Performance tip: Constructing an XmlSerializer is expensive. Keep a reference to your XmlSerializer instance if you intend to parse/write multiple XML files.

    ReplyDelete
  4. What's wrong with XmlTextReader, XmlReader, XmlNodeReader and the System.Xml.XPath namespace? (XPathNavigator, XPathDocument, XPathExpression, XPathnodeIterator)?

    Usually XPath makes reading XML easier, which is what you might be looking for.
    Sometimes I cry

    ReplyDelete