c# - How do I get the contents of an XML element using a XmlSerializer? -
i have xml reader on xml string:
<?xml version="1.0" encoding="utf-8" ?> <story id="1224488641nl21535800" date="20 oct 2008" time="07:44"> <title>press digest - portugal - oct 20</title> <text> <p> lisbon, oct 20 (reuters) - following of main stories in portuguese newspapers on monday. reuters has not verified these stories , not vouch accuracy. </p> <p>more html stuff here</p> </text> </story>
i created xsd , corresponding class deserialization.
[system.xml.serialization.xmlrootattribute(namespace="", isnullable=false)] public class story { [system.xml.serialization.xmlattributeattribute()] public string id; [system.xml.serialization.xmlattributeattribute()] public string date; [system.xml.serialization.xmlattributeattribute()] public string time; public string title; public string text; }
i create instance of class using deserialize
method of xmlserializer.
xmlserializer ser = new xmlserializer(typeof(story)); return (story)ser.deserialize(xr);
now, text
member of story
null. how change story
class xml parsed expected?
edit:
using xmltext not work , have no control on xml i'm parsing.
i found very unsatisfactory solution.
change class (ugh!)
// ... [xmlelement("hack - should never match anything")] public string text; // ...
and change calling code (yuck!)
xmlserializer ser = new xmlserializer(typeof(story)); string text = string.empty; ser.unknownelement += delegate(object sender, xmlelementeventargs e) { if (e.element.name != "text") throw new xmlexception( string.format(cultureinfo.invariantculture, "unknown element '{0}' cannot deserialized.", e.element.name)); text += e.element.innerxml; }; story result = (story)ser.deserialize(xr); result.text = text; return result;
this bad way of doing because breaks encapsulation. there better way of doing it?
Comments
Post a Comment