Home > Mobile >  I am working on converting an XML file to CSV using C#. I have tried different approaches but cannot
I am working on converting an XML file to CSV using C#. I have tried different approaches but cannot

Time:09-23

This is the basic file layout.

<InvoiceNo>1065178</InvoiceNo>
<InstallationId>10903</InstallationId>
<CreateDate>2019-03-29T00:00:00</CreateDate>
<AccountNo>123456</AccountNo>
<BalanceDue>1024.40</BalanceDue>
<StatementDate>2019-04-01T00:00:00</StatementDate>
<NoPrint>0</NoPrint>
<Pages>
<Page templatepage="1">
<OtherFields>
<Key name="Instructions1"><Value>Please write your account number on your check!</Value></Key>
<Key name="AgeTitle1"><Value>CURRENT </Value></Key>
<Key name="AgeTitle2"><Value>30 DAYS </Value></Key>
<Key name="AgeTitle3"><Value>60 DAYS </Value></Key>
<Key name="AgeTitle4"><Value>90 DAYS </Value></Key>
</OtherFields>
</Page>
</Pages>
</Invoice>

I can get the top level, Invoice No, Create Date but haven't been able to get to the key name/value pairs where most of the data is. Here is my latest try to get it loaded into a dictionary, it loads the entire node into one entry and i need to get it seperated. I am not invested in using the dictionary, it is simply my latest attempt. Any help would be greatly appreciated.

string xmlfile = @"C:/data//WDM/CUSTInvoiceData2019032902.xml";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(xmlfile);


XmlNodeList nodelist = xmldoc.SelectNodes("//*[local-name()='OtherFields']");
Dictionary<string, string> dictXml = new Dictionary<string, string>();

foreach (XmlNode node in nodelist)
{
    foreach (XmlNode elementpair in node.ChildNodes)
    {
        dictXml.Add(elementpair.Attributes["Key name"].Value, 
        elementpair.Attributes["value"].Value);
    }
}

CodePudding user response:

Almost done

  1. You fail on attribute name not .Attributes["Key name"] but .Attributes["name"]

  2. You must get the value and not the attribute, also you must get the child note value

    foreach (XmlNode elementpair in node.ChildNodes)
    {
        var key = elementpair.Attributes["name"].Value;
        var val = elementpair.ChildNodes[0].ChildNodes[0].Value;
        dictXml.Add(key,val);
    }

CodePudding user response:

You're selecting the Key elements and looking for two attributes: Key name and value. But the elements don't have attributes with those names. The key is in an attribute called name, and the corresponding value is in a child element (not an attribute) called Value.

  • Related