简体   繁体   中英

How would I parse this XML String?

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.

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

Define a root element

<root>
    <Summary>Foo</Summary>
    <Description>Bar</Desciption>
</root>

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM