Question

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();

Was it helpful?

Solution

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);
}

OTHER TIPS

Here's a sample program that does it using an XmlDocumentFragment, tested in .NET 2.0:

using System;
using System.Xml;
using System.Xml.XPath;

public class XPathTest
{
    public static void Main() {

        XmlDocument doc = new XmlDocument();
        string xmlnodestr = @"<mynode value1='1' value2='123'>abc</mynode>
<mynode value1='1' value2='123'>abc</mynode>
<mynode value1='1' value2='123'>abc</mynode>";

        XmlDocumentFragment frag = doc.CreateDocumentFragment();
        frag.InnerXml = xmlnodestr;

        XmlNodeList nodes = frag.SelectNodes("*");

        foreach (XmlNode node in nodes)
        {
            Console.WriteLine(node.Name + " value1 = {0}; value2 = {1}",
                              node.Attributes["value1"].Value,
                              node.Attributes["value2"].Value);
        }
    }
}

It produces the following output:

mynode value1 = 1; value2 = 123
mynode value1 = 1; value2 = 123
mynode value1 = 1; value2 = 123
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top