通过指定属性名称来解析xml

时间:2017-06-23 16:02:23

标签: c# xml linq-to-xml

我有一个xml,我只想从中解析特定属性而不是全部。我有100个属性,我提供的xml是一个属性很少的样本 。我想显式指定属性名称并解析它们的值。  例如:我想解析获取属性名称PersonN,VerifiedHuman的值 在我的逻辑中,我想通过指定<Name>PersonN</Name>等属性名称来解析值并解析其值 结果应该是csv。

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

我正在使用的逻辑:(我不知道如何指定属性名称并获取它们的值)在此代码中,str3是上面的xml。

using (XmlReader read = XmlReader.Create(new StringReader(str3)))
{

    bool isValue = false;
    while (read.Read())
    {
        if (read.NodeType == XmlNodeType.Element && read.Name == "Value")
        {
            isValue = true;
        }

        if (read.NodeType == XmlNodeType.Text && isValue)
        {
            output.Append((output.Length == 0 ? "" : ", ") + read.Value);
            isValue = false;
        }
    }

}

预期产出:

3, 2

2 个答案:

答案 0 :(得分:1)

很容易在字典中获取所有值。然后你只能提取你想要的那些。使用xml linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;


namespace ConsoleApplication63
{
    class Program
    {
        const string XML_FILENAME = @"c:\temp\test.xml";
        const string CSV_FILENAME = @"c:\temp\test.csv";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(XML_FILENAME);

            Dictionary<string, string> dict = doc.Descendants("Attribute")
                .GroupBy(x => (string)x.Element("Name"), y => (string)y.Element("Value"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

            StreamWriter writer = new StreamWriter(CSV_FILENAME);


            string[] attributesToRead = new[] { "CurrAddrTaxValue", "CurrAddrTaxMarketValue", "PrevAddrTaxValue" };
            //foreach (string attribute in attributesToRead)
            //{
            //    writer.WriteLine(string.Join(",", new string[] { attribute, dict[attribute] }));
            //}

            //all on one line

            string output = string.Join(",", attributesToRead.Select(x => dict[x]).ToArray());
            writer.WriteLine(output);

            writer.Flush();
            writer.Close();
        }
    }

}

答案 1 :(得分:1)

如果您想按产品对属性进行分组,则可以执行以下操作。

var document = XDocument.Load(fileName); // or `= XDocument.Parse(xml);`
var attributesToRead = new[] {"PersonN", "VerifiedHuman"};
var productsElements = document.XPathSelectElements("InterConnectResponse/ConsumerSubjects/ConsumerSubject/DataSourceResponses/RiskViewProducts");
var products = productsElements.Select(product => new
{
    Attributes = product.XPathSelectElements("RiskViewAttribResponse/Attributes/Attribute").Select(attribute => new
    {
        Name = attribute.Element("Name")?.Value,
        Value = attribute.Element("Value")?.Value
    }).Where(attribute => attributesToRead.Contains(attribute.Name))
});

要获得所需的输出,您可以执行此操作。

foreach (var product in products)
{
    foreach (var attribute in product.Attributes)
    {
        Console.WriteLine(attribute.Value + ", ");
    }
}

要创建csv,我建议您使用CsvHelper等库。

using (var writer = new StreamWriter(new FileStream(@"C:\mypath\myfile.csv", FileMode.Append)))
{
    var csv = new CsvWriter(writer);
    csv.Configuration.Delimiter = ",";
    foreach (var product in products)
    {
        foreach (var attribute in product.Attributes)
        {
            csv.WriteField(attribute.Value);
        }
        csv.NextRecord();
    }
}