根据变量从 xml 中获取项目列表
Get a list of items from xml according to variable
我正在寻找一个城市列表,其中一个国家等于 C# 中的一个变量
Here is a snippet of my xml
所以我想通过变量将阿富汗的城市加载到列表中。下面是我的代码,它显示了我的 xml 文件中的所有值。
XmlReader reader = new XmlTextReader(@"Countries_Cities.xml");
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == "title")
{
string title = reader.ReadElementString();
Debug.WriteLine("Country Name: " + title);
}
if (reader.NodeType == XmlNodeType.Element && reader.Name == "city")
{
string city = reader.ReadElementString();
Debug.WriteLine("* " + city);
}
}
使用 Xml Linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication18
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
public static void Main(String[] args)
{
XDocument doc = XDocument.Load(FILENAME);
string[] cities = doc.Descendants("country").Where(x => (string)x.Element("title") == "Afghanistan").Descendants("city").Select(x => (string)x).ToArray();
}
}
}
我正在寻找一个城市列表,其中一个国家等于 C# 中的一个变量
Here is a snippet of my xml
所以我想通过变量将阿富汗的城市加载到列表中。下面是我的代码,它显示了我的 xml 文件中的所有值。
XmlReader reader = new XmlTextReader(@"Countries_Cities.xml");
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == "title")
{
string title = reader.ReadElementString();
Debug.WriteLine("Country Name: " + title);
}
if (reader.NodeType == XmlNodeType.Element && reader.Name == "city")
{
string city = reader.ReadElementString();
Debug.WriteLine("* " + city);
}
}
使用 Xml Linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication18
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
public static void Main(String[] args)
{
XDocument doc = XDocument.Load(FILENAME);
string[] cities = doc.Descendants("country").Where(x => (string)x.Element("title") == "Afghanistan").Descendants("city").Select(x => (string)x).ToArray();
}
}
}