Home > Blockchain >  C# XML - getting an optional tag?
C# XML - getting an optional tag?

Time:06-21

I have xml with the following:

     <sample intentref="BIZ_hello" count="1">hey</sample>
     <sample intentref="business_status" count="1">status of my order</sample>
     <sample intentref="business_status" count="1">order for my number<annotation conceptref="o_number">12343</annotation>

And I'm trying to build a list like this:

Intent Sample Count Annotation
BIZ_hello hey 1 NONE
business_status status of my order 1 NONE
business_status order for my number 1 "<annotation conceptref=o_number>12343</annotation>"

I'm stuck at getting the 'annotated text' part. The code I have so far that works for 'intent' and 'sample' and 'count'...I'm trying to get that optional '' tag .

XmlDocument xdoc = new XmlDocument();
xdoc.Load(fileName);

XmlNodeList nodes = xdoc.SelectNodes("project/samples/sample");

foreach (XmlNode xn in nodes)
{

    ParseList tempList = new ParseList();
    tempList.intentName = xn.Attributes["intentref"]?.Value ?? "Unassigned";
    tempList.sampleSentence = xn.FirstChild.Value;
    tempList.countSamples = xn.Attributes["count"].Value;
    tempList.annotatedText = ???

}

CodePudding user response:

You can use the following

tempList.annotatedText = xn["annotation"]?.OuterXml ?? "NONE";

The ? deals with the case when the node is not there. OuterXml returns the whole child node as text.

  • Related