有没有办法检查 XML-File 中的特定节点是否包含评论以及它是否阅读评论?

Is there a way to check if a specific Node from a XML-File contains a comment and if it does to read the comment?

我想读取来自特定节点的所有评论并将它们放入 C# 中的列表中。

我的密码是:

List<string> keyList = new List<string>();
List<string> valueList= new List<string>();

var xmldoc = new XmlDocument();
xmldoc.Load("xmlfile.xml");

var result = xmldoc.SelectNodes(/manuel/chapter-ref/chapter/chapter-ref/chapter/block/procedure/step/action/table/tgroup/tbody/row/entry/p/formfield/@field_id);

foreach(XmlNode item in result){
keyList.Add(item.Value)
}

这样我就可以从表单域中获取每个 field_id 并将它们放入 keyList 中。有些表单域包含注释,有些则不包含。我想将这些评论添加到列表 valueList 中,如果表单域不包含评论,我想将 "no value" 添加到列表中。有办法吗?

Select 使用 foo/bar/comment()

在 XPath 中注释

由于您已经向表单域调用 SelectNodes,我建议更改 XPath 并添加一个 if 语句来检查注释节点。

List<string> keyList = new List<string>();
List<string> valueList= new List<string>();

var xmldoc = new XmlDocument();
xmldoc.Load("xmlfile.xml");

// Removed '/@field_id'
var result = xmldoc.SelectNodes("/manuel/chapter-ref/chapter/chapter-ref/chapter/block/procedure/step/action/table/tgroup/tbody/row/entry/p/formfield");

foreach(XmlElement item in result)
{
    var nd = item.SelectSingleNode("comment()");
    if (nd != null) valueList.Add(nd.InnerText);
    else valueList.Add("no val");

    keyList.Add(item.GetAttribute("field_id")); // Changed to GetAttribute
}

使用 xml liinq :

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:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            var comments = doc.DescendantNodes().Where(x => x.GetType() == typeof(XComment)).ToList();            
         }
    }
}