Search code examples
c#xml-parsinglinq-to-xmlxelement

Can't Retrieve Values of XML Elements using XElement


I am trying to read from an XML file that is supplied through a file browser but the values are alwas null even though I can see the xml file come through to elements.

  public void UploadXml(Stream fileStream)
  {
    //Load xml
      fileStream.Position = 0;

      var xdoc = XElement.Load(fileStream);

      IEnumerable<XElement> elements = xdoc.Elements();

      var codeList = new CodeList();

      foreach (var item in elements)
      {
          codeList.Name = item.Element("CODELIST_NAME").Value;
          codeList.Description = item.Element("DESRIPTION").Value;
          codeList.Version = item.Element("VERSION").Value;
          codeList.EffectiveDate = DateTime.Parse(item.Element("EFFECTIVE_DATE").Value);
          codeList.ExpirationDate = DateTime.Parse(item.Element("EXPIRATION_DATE").Value);
      }
      // save code list

      // get code list ID

      // create codes
  }

UPDATE XML

<?xml version="1.0" encoding="utf-8"?>
<CONTEXT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"    
         xmlns="http://www.w3.org/2000/xmlns">
  <CONTEXT_NAME></CONTEXT_NAME>
  <CODELIST>
    <CODELIST_NAME></CODELIST_NAME>
        <DESRIPTION></DESRIPTION>
        <VERSION></VERSION>
        <USERNAME>test user</USERNAME>
        <OWNER_TEAM />
        <STEWARD_TEAM />
        <STATUS></STATUS>
        <LAST_MODIFIED></LAST_MODIFIED>
        <LAST_MODIFIED_NAME></LAST_MODIFIED_NAME>
        <EFFECTIVE_DATE></EFFECTIVE_DATE>
        <EXPIRATION_DATE></EXPIRATION_DATE>
        <FILE_TIMESTAMP></FILE_TIMESTAMP>
       <CONSTRAINED_VALUE>
           <CODE></CODE>
           <PARENT_ID />
           <NAME></NAME>
           <DESCRIPTION></DESCRIPTION>
       </CONSTRAINED_VALUE>
 </CODELIST>
</CONTEXT>

In a normal file there would be data in the file obviously I just had to remove it for the sample.

The constrained value tags will be repeated for rows in a database


Solution

  • Thanks for the help, it was useful for me to fix this

    My problem was with how I was reading the values.

    xdoc.Element(XName.Get("CODELIST", dns.NamespaceName)).Element(XName.Get("CODELIST_NAME", dns.NamespaceName)).Value,
    

    Reading it this way has fixed it for me.