我想从特定节点读取所有注释,并将它们放入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)
}
这样,我可以从formfields中获取每个field_id并将其放入keyList中。有些表单域包含注释,而有些则不包含注释。我想将这些注释添加到列表valueList中,如果formfield不包含注释,则要将“无值”添加到列表中。有办法吗?
答案 0 :(得分:1)
使用foo/bar/comment()
由于您已经向formfield调用了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
}
答案 1 :(得分:0)
使用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();
}
}
}