Parse node string to XMLNodeList

wonea picture wonea · Nov 17, 2011 · Viewed 12.5k times · Source

I'm curious, what would be the neatest way to parse a string of xml nodes to a XmlNodeList. For example;

string xmlnodestr = "<mynode value1='1' value2='123'>abc</mynode>
<mynode value1='1' value2='123'>abc</mynode>
<mynode value1='1' value2='123'>abc</mynode>";

I could possibly do a string split on the list, but that would be messy and non-proper.

Ideally I want something like;

XmlNodeList xmlnodelist = xmlnodestr.ParseToXmlNodeList();

Answer

Ahmad Mageed picture Ahmad Mageed · Nov 17, 2011

You could add a root to your XML then use this approach:

string xmlnodestr = @"<mynode value1=""1"" value2=""123"">abc</mynode><mynode value1=""1"" value2=""123"">abc</mynode><mynode value1=""1"" value2=""123"">abc</mynode>";
string xmlWithRoot = "<root>" + xmlnodestr + "</root>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlWithRoot);
XmlNodeList result = xmlDoc.SelectNodes("/root/*");

foreach (XmlNode node in result)
{
    Console.WriteLine(node.OuterXml);
}

If you can use LINQ to XML this would be much simpler, but you wouldn't be working with an XmlNodeList:

var xml = XElement.Parse(xmlWithRoot);
foreach (var element in xml.Elements())
{
    Console.WriteLine(element);
}