Home > database >  How to display attributes and skip when necessary in C#
How to display attributes and skip when necessary in C#

Time:06-15

string str = "<samples><sample>cancel</sample><sample intentref='BUSINESS_PAY'>make payment</sample></samples>";
XmlDocument xml = new XmlDocument();
xml.LoadXml(str);  

XmlNodeList xnList = xml.SelectNodes("/samples/sample");
foreach (XmlNode xn in xnList)
{
    
    string intent = xn.Attributes["intentref"].Value;
    Console.WriteLine(intent);
}

If you look at the (str) variable, you can see the XML tags. As you can see, some of the elements don't have 'intentref' attribute and some do. What I'm trying to do is print it like this:

Intent Sample
Unassigned cancel
BUSINESS_PAY make payment

Thanks,

CodePudding user response:

string intent = xn.Attributes["intentref"]?.Value ?? "Unassigned";

See it work here:

https://dotnetfiddle.net/ELgyJ6

  • Related