我有大量具有大量属性的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>
我想从中获得1960年的Aruba和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']]],但对我来说没有任何解决办法。
答案 0 :(得分:0)
这是使用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;}
}
}