Parsing external XML file with C#, what's the most aesthetic way?
say there is an xml file, which not created by me, with a known schema (for example, rss开发者_如何学C).
how would you parse it with C#? would you do that manually by XDocument etc, or would you use XMLSerializer and create a correspond class? or would you use Visual Studio tools to generate classes using a dtd file (that you'll write).
what do you think the most aesthetic, easy, not error-prone way?
Have a look at the XmlReader class (and subclasses)
http://msdn.microsoft.com/en-us/library/aa720470(VS.71).aspx
In my opinion, the easiest method in terms of coding difficulty would be to generate an object model off of the schema, and use that with the XmlSerializer to go back and forth between objects and XML. There is a tool called xsd.exe that comes with Visual Studio that can generate code from xsd files.
That said, if the schema is complex or written by a dinosaur, the object model will be ugly and hard to use. If your XML is archaic or poorly written/designed, sometimes it's easier to just manipulate it directly using XmlDocument or XDocument. Out of those two, I'd prefer the newer LINQ to XML model (XDocument), because it's easier to search the XML, and it's easier to insert or manipulate elements/attributes/etc.
I would use XLINQ to parse it if I don't have an object model for the XML, and XmlSerializer if I do.
In the past, I ( and my company ) have used DataSets and the Load/SaveXML methods.
Have a look at System.Xml.Linq Namespace
Has some very good classes such as XElement and XDocument and many more. Will help you cruise through xml parsing
精彩评论