首页 > 解决方案 > 我正在使用 C# 将 XML 文件转换为 CSV。我尝试了不同的方法,但无法弄清楚如何访问键名/值对

问题描述

这是基本的文件布局。

<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>

我可以得到顶层,发票编号,创建日期,但无法访问大部分数据所在的键名/值对。这是我最近尝试将其加载到字典中,它将整个节点加载到一个条目中,我需要将其分开。我没有投入使用字典,这只是我最近的尝试。任何帮助将不胜感激。

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);
    }
}

标签: c#xml

解决方案


快完成了

  1. 您在属性名称上失败了,.Attributes["Key name"].Attributes["name"]

  2. 您必须获取值而不是属性,还必须获取子注释值

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

推荐阅读