C# 在xml中搜索特定值
我有一个特殊的xml文件元素。如果参数名称为“宗教名称”,我想获取参数值。如何使用C#使用LINQ进行搜索C# 在xml中搜索特定值,c#,xml,C#,Xml,我有一个特殊的xml文件元素。如果参数名称为“宗教名称”,我想获取参数值。如何使用C#使用LINQ进行搜索 读取并加载xml文件 搜索参数名称 获取参数值 宗教名称 罗马天主教 名称 詹姆斯·史密斯 var doc=new XmlDocument(); doc.LoadXml(“\r\n\r\n宗教名称\r\n罗马天主教名称\r\n\r\n\r\n名称\r\n詹姆斯·史密斯\r\n\r\n”); var nameList=doc.GetElementsByTagName(“参数名”); var
宗教名称
罗马天主教
名称
詹姆斯·史密斯
var doc=new XmlDocument();
doc.LoadXml(“\r\n\r\n宗教名称\r\n罗马天主教名称\r\n\r\n\r\n名称\r\n詹姆斯·史密斯\r\n\r\n”);
var nameList=doc.GetElementsByTagName(“参数名”);
var valueList=doc.GetElementsByTagName(“参数值”);
for(int i=0;i
我喜欢为这些类型的程序使用字典
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication132
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Dictionary<string, string> dict = doc.Descendants("context-param")
.GroupBy(x => (string)x.Element("param-name"), y => (string)y.Element("param-value"))
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
string religion = dict["Religion Name"];
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Xml;
使用System.Xml.Linq;
命名空间控制台应用程序132
{
班级计划
{
常量字符串文件名=@“c:\temp\test.xml”;
静态void Main(字符串[]参数)
{
XDocument doc=XDocument.Load(文件名);
Dictionary dict=doc.substands(“上下文参数”)
.GroupBy(x=>(字符串)x.Element(“参数名称”),y=>(字符串)y.Element(“参数值”))
.ToDictionary(x=>x.Key,y=>y.FirstOrDefault());
字符串religure=dict[“宗教名称”];
}
}
}
类似问题:这是示例xml文件。从web.xml文件读取这是示例xml文件。阅读web.xml文件请修改您的帖子,因为您不需要web.xml文件
var doc = new XmlDocument();
doc.LoadXml("<root>\r\n <context-param>\r\n <param-name>Religion Name</param-name>\r\n <param-value>Roman Catholic</param-value>\r\n </context-param>\r\n <context-param>\r\n <param-name>Name</param-name>\r\n <param-value>James Smith</param-value>\r\n </context-param>\r\n</root>");
var nameList = doc.GetElementsByTagName("param-name");
var valueList = doc.GetElementsByTagName("param-value");
for (int i = 0; i < nameList.Count; i++)
{
if (nameList[i].InnerXml.Equals("Religion Name"))
{
//get your value
var value= valueList[i].InnerXml;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication132
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Dictionary<string, string> dict = doc.Descendants("context-param")
.GroupBy(x => (string)x.Element("param-name"), y => (string)y.Element("param-value"))
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
string religion = dict["Religion Name"];
}
}
}