[英]Getting Values from XML
我有一個XML文件,其中填充了如下所示的值:
<property name ="Web Application" value="\Fxnet2\Web\webpl\" />
<property name="Web Service" value="\FXnet2\Web\FXnet_SC_WS\" />
對於每一行,我想將名稱導入一個字符串(稱為serviceName),並將值導入另一個字符串(稱為servicePath)。
我在xml中得到了約250行的排序,是否有可能以當前的xml格式進行呢? 如果是怎么辦? ,還是應該更改列表的格式?
提前致謝 。
您可以獲取所有節點並循環訪問它們的屬性。 在下面的示例中,我將這兩個屬性的值添加到2個不同的數組中,您以后可以輕松地對其進行操作。
XmlDocument doc = new XmlDocument();
doc.Load("yourfile.xml");
XmlNodeList usernodes = doc.SelectNodes("//property");
//Declare arrays
List<string> serviceName = new List<string>();
List<string> servicePath = new List<string>();
//iterate through all elements found
foreach (XmlNode usernode in usernodes)
{
serviceName.Add(usernode.Attributes["name"].Value);
serviceName.Add(usernode.Attributes["value"].Value);
}
最終做到了
static void Main(string[] args)
{
List<Service> services;
using(StreamReader file = File.OpenText("c:\\projects.xml"))
{
XDocument doc = XDocument.Load(file);
services = (from node in doc.Root.Elements("property")
select new Service
{
serviceName = node.Attribute("name").Value,
servicePath = node.Attribute("value").Value,
dllFiles = System.IO.Directory.GetFiles( "servicePath", "*.dll" ),
}).ToList<Service>();
}
使用XML Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input =
"<Root>" +
"<property name =\"Web Application\" value=\"\\Fxnet2\\Web\\webpl\" />" +
"<property name=\"Web Service\" value=\"\\FXnet2\\Web\\FXnet_SC_WS\" />" +
"</Root>";
XElement root = XElement.Parse(input);
var results = root.Descendants("property").Select(x => new {
name = x.Attribute("name").Value,
value = x.Attribute("value").Value
}).ToList();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.