繁体   English   中英

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

[英]How would I parse this XML String?

我有一个像这样的XML字符串:

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

我想将此读入一个类对象:

class Foobar()
{
    string Summary {get;set;}
    string Description {get;set;}
}

我尝试使用XmlTextReader,但是它引发了一个异常,即找不到根元素。 这是我试过的:

using (XmlTextReader reader = new XmlTextReader(new StringReader(comment)))
{
     while (reader.Read())
     //do something here
}

我还尝试过将其反序列化为这样的对象:

[XmlTypeAttribute]    
    public class Foobar
    {

        [XmlElementAttribute("Summary")]
        public string Summary { get; set; }

        [XmlElementAttribute("Description")]
        public string Description { get; set; }        

    }

这也失败了,因为我没有为Foobar类定义[XmlRootElement] ,因为没有根元素。

您需要为您的xaml设置根元素

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

对于XMLSeralizatoion中的Rootlement: http : //msdn.microsoft.com/zh-cn/library/system.xml.serialization.xmlrootattribute.aspx

定义根元素

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

最简单的方法可能是手动添加根元素。

string xml = "<root>" + comment + "</root>";

然后,您可以使用所需的任何方法对其进行解析。

使用允许XMLFragments的构造函数形式(如果将XML块放入单个元素中可能是有效的,但并非如此):

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

更好的是,使用Create() ,它仍然提供更多的灵活性。

暂无
暂无

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

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