I want to read all comments from specific Nodes and put them into a List in C#.
My Code is:
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)
}
This way I can get every field_id from the formfields and put them into the keyList. Some formfields contain a comment and some don't. I want to add those comments into the list valueList and if the formfield doesn't contain a comment I want to add "no value" into the list. Is there a way to do so?
Select comments in XPath using foo/bar/comment()
Since you already call SelectNodes
towards the formfield I suggest changing the XPath and add an if statement checking for the comment node.
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
}