user4963104
user4963104

Reputation: 120

XPath show null if empty value

If we have this XML file, how can we use XPath to select several items in one object?

<CATALOG>
   <CD>
      <TITLE>Empire Burlesque</TITLE>
      <ARTIST>Bob Dylan</ARTIST>
      <COUNTRY>USA</COUNTRY>
      <PRICE>10.90</PRICE>
      <YEAR>1985</YEAR>
   </CD>
   <CD>
      <TITLE>Hide your heart</TITLE>
      <ARTIST>Bonnie Tyler</ARTIST>
   </CD>
   <CD>
      <TITLE>Greatest Hits</TITLE>
      <COMPANY>RCA</COMPANY>
      <PRICE>9.90</PRICE>
      <YEAR>1982</YEAR>
   </CD>
</CATALOG>

Objects needed should have:

myObj[0].TITLE = "Empire Burlesque"; 
myObj[0].ARTIST = "Bob Dylan";
myObj[0].COUNTRY = "USA";

myObj[1].TITLE = "Hide your heart"; 
myObj[1].ARTIST = "Bonnie Tyler";
myObj[1].COUNTRY = NULL;

myObj[2].TITLE = "Greatest Hits"; 
myObj[2].ARTIST = NULL;
myObj[2].COUNTRY = NULL;

My first ideas were to use some multiselect XPath, or to select 3 lists (3 different xpaths), but i'm not sure how to return NULL where element does not exists.

Upvotes: 1

Views: 883

Answers (1)

Rubens Farias
Rubens Farias

Reputation: 57996

You can have a method to deal with the inner element presence, like below. But, if you're transforming an XML file to a C# object, maybe you can take a look into the Serialization attribute.

class Program
{
    static void Main(string[] args)
    {

        var doc = new XmlDocument();
        doc.LoadXml(@"<CATALOG>...</CATALOG>");

        var items = new List<CompactDisk>();
        foreach (XmlElement cd in doc.SelectNodes("//CD"))
        {
            items.Add(new CompactDisk
            {
                Title = GetValue(cd, "TITLE"),
                Artist = GetValue(cd, "ARTIST"),
                Country = GetValue(cd, "COUNTRY"),
            });

        }
    }

    static string GetValue(XmlElement node, string xpath)
    {
        var result = node.SelectSingleNode(xpath);
        return result == null ? null : result.InnerText;
    }

    class CompactDisk
    {
        public string Title   { get; set; }
        public string Artist  { get; set; }
        public string Country { get; set; }
    }
}

Upvotes: 1

Related Questions