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