将节点字符串解析为XMLNodeList

时间:2011-11-17 17:01:16

标签: c# xmlnodelist

我很好奇,将一串xml节点解析为XmlNodeList的最佳方法是什么。例如;

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

我可能会在列表中进行字符串拆分,但这将是混乱和不正确的。

理想情况下,我想要类似的东西;

XmlNodeList xmlnodelist = xmlnodestr.ParseToXmlNodeList();

2 个答案:

答案 0 :(得分:3)

您可以在XML中添加根,然后使用此方法:

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

如果您可以使用LINQ to XML,这会更简单,但您不会使用XmlNodeList

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

答案 1 :(得分:2)

这是一个使用XmlDocumentFragment进行测试的示例程序,在.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);
        }
    }
}

它产生以下输出:

mynode value1 = 1; value2 = 123
mynode value1 = 1; value2 = 123
mynode value1 = 1; value2 = 123