2

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.

4 Answers 4

3

Define a root element

<root>
    <Summary>Foo</Summary>
    <Description>Bar</Desciption>
</root>
Sign up to request clarification or add additional context in comments.

5 Comments

What if that isn't an option? If absolutely required, I could do it, but I would prefer not requiring a root element
You will always need to have a root element or else how can you parse and run query. Also, how will your code understand where to start and where to end.
Alright, nevermind. I buckled under and added a root element. Thanks for the heads up. Will accept in 5min
If that is not an option you DO NOTH AVE VALID XML. Ups. Looks QUITE similar to XML, but is not.
Well, it should always be an option, since you can feed in the root element's tags. Still, while you don't have a valid XML document, you do have a well-formed XML fragment, and XmlTextReader can be constructed such that it accepts XML fragments, so root elements most certainly aren't required.
3

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

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.