将节点字符串解析为XMLNodeList
本文关键字:XMLNodeList 节点 字符串 | 更新日期: 2023-09-27 18:15:13
我很好奇,将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();
您可以在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);
}
下面是一个使用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