4

我很好奇,将一串 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();

4

2 回答 2

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);
}
于 2011-11-17T17:10:18.857 回答
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
于 2011-11-17T17:13:06.063 回答