c# - 我正在使用 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);
}
}
解决方案
快完成了
您在属性名称上失败了,
.Attributes["Key name"]
但.Attributes["name"]
您必须获取值而不是属性,还必须获取子注释值
foreach (XmlNode elementpair in node.ChildNodes)
{
var key = elementpair.Attributes["name"].Value;
var val = elementpair.ChildNodes[0].ChildNodes[0].Value;
dictXml.Add(key,val);
}
推荐阅读
- python - 读取本地状态/检查点值 Pulumi
- python - python dataframe drop().index 混淆
- openflow - 使用 openflow 拒绝(而不是!只是丢弃)数据包
- angular - Angular 中带有 CustomWeback 的 ImageminPlugin 在生产环境中不起作用
- signal-processing - 在一个 SPI 端口和一个片选上连接 DSP 与 ADC 和 DAC 数据转换器
- php - 如何删除最后一页使用 PHP 的历史记录?
- php - 使用 PHP Imagick 将 ICO 转换为 PNG
- django - 如何在我的 Django Modelform 中进行自定义验证?
- php - Apache 2,PHP - HTTP GET 域上的问题
- python - numpy - 像字典一样使用数组