Reputation: 42450
I have an XML string like this:
<Summary>Foo</Summary><Description>Bar</Description>
I want to read this into a class object:
class Foobar()
{
string Summary {get;set;}
string Description {get;set;}
}
I tried using XmlTextReader, but it throws an exception that no root element was found. This is what I tried:
using (XmlTextReader reader = new XmlTextReader(new StringReader(comment)))
{
while (reader.Read())
//do something here
}
I also tried deserializing it directly into an object like this:
[XmlTypeAttribute]
public class Foobar
{
[XmlElementAttribute("Summary")]
public string Summary { get; set; }
[XmlElementAttribute("Description")]
public string Description { get; set; }
}
This fails as well because I cannot define a [XmlRootElement]
for the class Foobar, since there is no root element.
Upvotes: 2
Views: 104
Reputation: 113352
Use a constructor form that allows for XMLFragments (chunks of XML that could be valid if put into a single element, but which are not so-rooted):
using (XmlTextReader reader = new XmlTextReader(comment, XmlNodeType.Element, null))
{
while (reader.Read())
//do something here
}
Better yet, use Create()
, which gives more flexibility still.
Upvotes: 0
Reputation: 39017
The easiest way is probably to manually add a root element.
string xml = "<root>" + comment + "</root>";
Then you can parse it with whichever method you want.
Upvotes: 1
Reputation: 13594
Define a root element
<root>
<Summary>Foo</Summary>
<Description>Bar</Desciption>
</root>
Upvotes: 3
Reputation: 176956
You need to set root element for that your xaml would be
<root>
<Summary>Foo</Summary><Description>Bar</Description>
</root>
For Rootelement in XMLSeralizatoion : http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlrootattribute.aspx
Upvotes: 3