c# - Can I use XMLReader to create objects representing elements in the document? -
I have a need to use a very large XML files so I XMLReader is the need to parse me this file There is a large number of elements of second level, which contains the information that I am interested in eg:
& lt; TopLevelElement & gt; & Lt; SecondLevelElement & gt; & Lt; Information1 & gt; Blah & lt; / Information1 & gt; & Lt; Info 2 & gt; Blah & lt; / Information 2 & gt; & Lt; Information3 & gt; Blah & lt; / Information3 & gt; & Lt; / SecondLevelElement & gt; & Lt; SecondLevelElement & gt; .... & lt; / TopLevelElement & gt;
person other level elements are not very big, I'll be glad to personally every load as an object and based on the schema of the file structure of my reader code I would like to parse that I am trying to parse
I have used xsd.exe to create objects from my schema and tried this:.
while (lReader.Read ()) {if (lReader.Name == "SecondLevelElement") {MyXml.SecondLevelElement lSecondLevelElement = lReader.ReadElementContentAs (typeof (MyXml.SecondLevelElement), NULL) MyXml .SecondLevelElement; If (lSecondLevelElement! = NULL) {// do stuff}}}
But it fails with a very helpful exception ReadElementContentAs (). Examples of MSDN show only this method used on very basic data types, so I am not entirely sure that I can do this too.
So my first question is also possible, or do I bark my time completely wrong tree? Is there a way to parse XML classes without having to match XSD closely to my reading code?
Edit After implementing Powell's answer I got the error of errors. In my case which was under the XSD I was using automatic classes to generate Since I had an XSD for the entire document, the second level element class name did not match the actual element name. To fix this, I removed the top-level element from my XSD schema and rebuilt the orbits. Having done that after all this has worked perfectly.
ReadElementContentAs
only works with a predefined int ,
date time
etc. It is not used with the types generated by xsd.exe
- they are controlled by XML Serializer
:
Private Static Readonly XML serializer second level elementiserializer = new XML sensilizer (typef (secondary second level element)); ... XmlReader Reader; While (reader.Read ()) {... switch (reader.Name) {case "SecondLevelElement"}: {MyXml.SecondLevelElement elem = (MyXml.SecondLevelElement) secondLevelElementSerializer.Deserialize (reader); ... } break; ...}}
Comments
Post a Comment