[英]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.