从字符串解析XML数据
问题描述:
我想要做的是从字符串中获取xml数据而不是txt文件。这工作:从字符串解析XML数据
// xmlData.txt contains < m t='Hello' u='1337' />
XmlReader config = new XmlTextReader("../../xmldata.txt");
config.Read();
Console.WriteLine("Data: " + config.GetAttribute("t"));
但我想解析它从字符串而不是文档。
如何解析字符串中的XML数据?
答
使用StringReader
和饲料它的XmlTextReader
:
StringReader sr = new StringReader("<m t='Hello' u='1337'/>");
XmlReader config = new XmlTextReader(sr);
config.Read();
Console.WriteLine("Data: " + config.GetAttribute("t"));
+0
感谢。如果其他人正在阅读本文,则需要使用System.IO:p – SwagBob 2015-01-31 21:00:25
+1
正确,但@SwagBob,XmlReader仍然是错误的工具。这很麻烦,用于非常大的文件/流。确保你知道'class XElement'。 – 2015-01-31 21:04:13
此外,您还可以使用System.Xml.Linq.XDocument.Parse( “串......”) – Crowcoder 2015-01-31 20:40:15