在C#中将字符串转换为XmlNode的更好方法
问题描述:
我想将字符串(显然是xml)转换为C#中的XmlNode.在网上搜索时,我得到了这段代码.我想知道这是否是将字符串转换为XmlNode的好方法?我必须在循环中执行此转换,所以它会引起性能问题吗?
I wanted to convert a string (which obviously is an xml) to an XmlNode in C#.While searching the net I got this code.I would like to know whether this is a good way to convert a string to XmlNode? I have to preform this conversion within a loop, so does it cause any performace issues?
XmlTextReader textReader = new XmlTextReader(new StringReader(xmlContent));
XmlDocument myXmlDocument = new XmlDocument();
XmlNode newNode = myXmlDocument.ReadNode(textReader);
请回复
谢谢
亚历克斯
答
应该简单明了:
string xmlContent = "<foo></foo>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlContent);
XmlNode newNode = doc.DocumentElement;
或使用LINQ(如果可以的话):
or with LINQ if that's an option:
XElement newNode = XDocument.Parse(xmlContent).Root;