简体   繁体   English

我将如何解析此XML字符串?

[英]How would I parse this XML String?

I have an XML string like this: 我有一个像这样的XML字符串:

<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. 我尝试使用XmlTextReader,但是它引发了一个异常,即找不到根元素。 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. 这也失败了,因为我没有为Foobar类定义[XmlRootElement] ,因为没有根元素。

You need to set root element for that your xaml would be 您需要为您的xaml设置根元素

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

For Rootelement in XMLSeralizatoion : http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlrootattribute.aspx 对于XMLSeralizatoion中的Rootlement: http : //msdn.microsoft.com/zh-cn/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): 使用允许XMLFragments的构造函数形式(如果将XML块放入单个元素中可能是有效的,但并非如此):

using (XmlTextReader reader = new XmlTextReader(comment, XmlNodeType.Element, null))
{
     while (reader.Read())
     //do something here
}

Better yet, use Create() , which gives more flexibility still. 更好的是,使用Create() ,它仍然提供更多的灵活性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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