簡體   English   中英

如何從具有特定屬性的xml元素中獲取值?

[英]How to get the values out of xml-elements with specific attributes?

我有大量具有大量屬性的xml數據,我想從包含特定屬性的xml行中解析值。 這是xml數據:

<Root xmlns:wb="http://www.worldbank.org">
  <data>
    <record>
      <field name="Country or Area" key="ABW">Aruba</field>
      <field name="Item" key="SP.URB.TOTL.IN.ZS">Urban population (% of total)</field>
      <field name="Year">1960</field>
      <field name="Value">50.776</field>
    </record>
 </data>
</Root>

我想得到Aruba,1960和50.776。

我試過這個:

XmlDocument xml = new XmlDocument();
              xml.Load("daten.xml");
XmlNodeList list = xml.SelectNodes("//data/record/field");
            foreach (XmlNode item in list)
            {
                Console.WriteLine(item.Attributes["Name"].Value);
            }

這個引發了一個例外,但是我還試着使用item [“field”]或item [“field @ [name ='Year']],但是沒有任何方法可以解決。

以下是使用xml linq的一種方法:

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

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

            List<Record> records = new List<Record>();
            foreach (XElement record in doc.Descendants("record"))
            {
                Record newRecord = new Record();
                records.Add(newRecord);
                foreach (XElement field in record.Elements("field"))
                {
                    string name = (string)field.Attribute("name");

                    switch (name)
                    {
                        case "Country or Area":
                            newRecord.country_area_key = (string)field.Attribute("key");
                            newRecord.country_area_name = (string)field;
                            break;

                        case "Item":
                            newRecord.item_key = (string)field;
                            break;

                        case "Year":
                            newRecord.year = (int)field;
                            break;

                        case "Value":
                            newRecord.value = (decimal)field;
                            break;
                    }
                }
            }

        }
    }
    public class Record
    {
        public string country_area_key { get;set;}
        public string country_area_name { get;set;}
        public string item_key { get;set;}
        public int year { get;set;}
        public decimal value { get;set;}
    } 

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM