C#:使用Xdocument分析XML到CSV文件中



我有几个格式的XML:

<InterConnectResponse>
  <SchemaVersion>2.0</SchemaVersion>
  <ConsumerSubjects>
    <ConsumerSubject subjectIdentifier="Primary">
      <DataSourceResponses>
      <RiskViewProducts>
          <RiskViewAttribResponse>
          <Attributes>
                <Attribute>
                  <Name>CurrAddrTaxValue</Name>
                  <Value>3</Value>
                </Attribute>
                <Attribute>
                  <Name>CurrAddrTaxMarketValue</Name>
                  <Value>2</Value>
                </Attribute>
                <Attribute>
                  <Name>CurrAddrBlockIndex</Name>
                  <Value>0.61</Value>
                </Attribute>
           ------ Many More Attributes ---------
         </Attributes>
         </RiskViewAttribResponse>
     </RiskViewProducts>
     </DataSourceResponses>
    </ConsumerSubject>
  </ConsumerSubjects>
</InterConnectResponse> 

我只想从上述XML解析特定属性。因此,我使用了以下logi。但是,如何将值(仅值为(作为CSV文件保存结果?

 var document = XDocument.Parse(str3); // or `= XDocument.Parse(xml);`
 var attributesToRead = new[] { "CurrAddrTaxValue", "CurrAddrTaxMarketValue", "PrevAddrTaxValue", "PrevAddrAVMValue", "AddrChangeCount60", "DerogSeverityIndex", "LienFiledCount03", "LienSmallClaimsFiledTotal", "EvictionCount12", "NonDerogCount", "NonDerogCount12", "InquiryPersonalFinanceRecent", "HighRiskCreditActivity", "SubPrimeOfferRequestCount", "SubPrimeOfferRequestCount60" };
 var productsElements = document.XPathSelectElements("InterConnectResponse/ConsumerSubjects/ConsumerSubject/DataSourceResponses/RiskViewProducts");
 var products = productsElements.Select(product => new
     {
         Attributes = product.XPathSelectElements("RiskViewAttribResponse/Result/Attributes/Attribute").Select(attribute => new
         {
              Name = attribute.XPathSelectElement("Name").Value,
              Value = attribute.XPathSelectElement("Value").Value
          }).Where(attribute => attributesToRead.Contains(attribute.Name))
     });

但是,如何将结果写入CSV中,该结果在我解析下一个XML时会附加?ASO我只想将值写入CSV而不是属性的名称。

所以我的预期输出是:

3, 2, 0.61,  ............

好吧,您的products变量是匿名类型的IEnumerable,其属性名为AttributesAttributes属性是匿名类型的IEnumerable,具有2个属性:NameValue

您想编写(准确地说(所有Value属性的内容到文件,然后执行此操作:

var values = products.SelectMany(x => x.Attributes).Select(x => x.Value);
File.AppendAllText("someFileName.csv", string.Join(",", values));

当然,我正在假设您的代码工作到那时,并且您只是附加到CSV文件的困难。

您是否考虑过为此使用库。使用Cinchoo ETL-开源ETL LIB,您可以使用几行代码生成预期的输出。它是基于流的,可以解析任何大小xml。

using (var parser = new ChoXmlReader("sample.xml").WithXPath("Attributes/Attribute")
    .WithField("Name", xPath: "Name")
    .WithField("Value", xPath: "value")
    )
{
    using (var writer = new ChoCSVWriter("sample.csv"))
        writer.Write(parser.Select(kvp => kvp.Value).ToExpandoObject());
}

输出为:

3,2,0.61

披露:我是这个图书馆的作者。

最新更新