【问题标题】: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?有没有办法检查 XML 文件中的特定节点是否包含评论以及是否可以读取评论?
【发布时间】:2020-06-16 17:58:10
【问题描述】:

我想从特定节点读取所有 cmets 并将它们放入 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 中。有些表单域包含注释,有些则不包含。我想将这些 cmets 添加到列表 valueList 中,如果表单字段不包含评论,我想将“无值”添加到列表中。有办法吗?

【问题讨论】:

  • 你能分享你的XML文件内容吗?
  • XML-File 是一个生成的文件,非常大。 6600 行。表单域如下所示: X,XXX

标签: c# xml list comments


【解决方案1】:

在 XPath 中使用 foo/bar/comment() 选择 cmets

由于您已经向表单域调用 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
}

【讨论】:

  • GetAttribute 是否仅适用于 XmlElement?我收到一条错误消息,说 XmlNode 不包含“GetAttribute”的定义。
  • 是的,但您的选择肯定是 XmlElements,只需将 foreach 中的 XmlNode 类型更改为 XmlElement。
  • 谢谢你,伙计!没看到你把它改成 XmlElement。它工作得非常好,正是我想要的!
【解决方案2】:

使用 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();            
         }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 2016-12-23
    • 2011-06-12
    • 2020-04-05
    • 1970-01-01
    • 2019-07-12
    • 2017-08-08
    相关资源
    最近更新 更多