我想通过XPath查找XML文件中多个节点的元素。节点的路径是:
(/章节/块/程序/步骤/动作/表/tgroup/tbody/row/entry/p/formfield(
我想从Childnode表单字段中获取Element字段_id。XML文件中有多个表单字段。所有路径都相同,但位于不同的行(/row(中。
我试过:
XmlDocument doc = new XmlDocument();
doc.Load("xmlfile.xml");
XmlNode node = doc.DocumentElement.SelectSingleNode("/chapter/block/procedure/step/action/table/tgroup/tbody/row/entry/p/formfield");
string attr = node.Attributes["field_id"]?.InnerText;
Console.WriteLine(attr);
这只给了我第一个表单字段中的field_id。我尝试了多种其他方法来获取每个ID,但我总是得到一个系统。NullReferenceException。如何获取每个field_id?
如果您共享示例XML,将会很容易。但是,您可以使用XmlDocument
尝试以下代码示例
var xmldoc = new XmlDocument();
xmldoc.Load("xmlfile.xml");
var result = xmldoc.SelectNodes("chapter/block/procedure/step/action/table/tgroup/tbody/row/entry/p/formfield/@field_id");
foreach (XmlNode item in result)
{
Console.WriteLine(item.Value);
}
还有另一种使用XDocument
和LINQ
的方法
var xdoc = XDocument.Load("xmlfile.xml");
var nodes = string.Join(", ", xdoc.Descendants("formfield")
.Select(x => x.Attribute("field_id")));
根据评论在下面添加代码
以下是使用XElement
读取XML注释的代码
var xdoc = XElement.Load("xmlfile.xml");
var comments = xdoc.DescendantNodes().OfType<XComment>();
foreach (XComment comment in comments)
{
//read comments here
}
您可以使用xml-linq并将结果放入字典中
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication159
{
class Program
{
const string FILENAME = @"c:temptest.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Dictionary<string, XElement> dict1 = doc.Descendants("formfield")
.GroupBy(x => (string)x.Attribute("field_id"), y => y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
//where attibutes may be repeated
Dictionary<string, List<XElement>> dict2 = doc.Descendants("formfield")
.GroupBy(x => (string)x.Attribute("field_id"), y => y)
.ToDictionary(x => x.Key, y => y.ToList());
}
}
}