[英]How to get the values out of xml-elements with specific attributes?
I have a big ton of xml-data with a lot of properties and I want to parse the values out of the xml-lines that contain specific properties. 我有大量具有大量属性的xml数据,我想从包含特定属性的xml行中解析值。 This is the xml data: 这是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>
I would like to get Aruba, 1960 and 50.776 out of this. 我想得到Aruba,1960和50.776。
I've tried this: 我试过这个:
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);
}
This one throws an exception, but I tried also other ways with item["field"] or item["field@[name='Year']], but nothing worked out for me. 这个引发了一个例外,但是我还试着使用item [“field”]或item [“field @ [name ='Year']],但是没有任何方法可以解决。
Here is one way using xml linq : 以下是使用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.