通过指定属性名称来解析xml [英] parse the xml by specifying the attribute names

查看:64
本文介绍了通过指定属性名称来解析xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个xml,我只想从中解析特定属性,而不是全部.我有100多个属性,而我提供的xml是带有少量属性的示例 .我想明确指定属性名称并解析它们的值. 例如:我想解析以获取属性名称PersonN,VerifiedHuman的值 按照我的逻辑,我想通过指定属性名称(例如<Name>PersonN</Name>)来解析值并解析其值 结果应该是csv.

I have a xml from which I want to parse only specific attributes not all. I have 100s of attributes and the xml I provided is a sample with few attributes . I want explicitly specify the attributes names and parse their values. Eg : I want to parse get the values of the Attribute names PersonN , VerifiedHuman In my logic I want to parse the values by specifying attribute names like <Name>PersonN</Name> and parse its value The result should be a 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.

Logic I am using : (I dont know how to specify the attribute names and get their values)In this code str3 is the above 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

推荐答案

很容易获得字典中的所有值.然后,您可以仅提取所需的内容.使用xml linq

It is easy to get all values in a dictionary. Then you can extract only the ones you want. Use 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();
        }
    }

}

这篇关于通过指定属性名称来解析xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆