读取特定的XML参数 [英] Reading specific XML parameter
问题描述
我目前正在从事一个项目,该项目必须读取xml文件以进行程序设置.
I'm currently working on a project in which a xml file must be read for program settings.
XML看起来像这样:
The XML looks like this:
<?xml version="1.0" encoding="utf-8"?>
<!-- Settings for Modul1 -->
<root>
<Program-Config>
<Parameter>Name</Parameter>
<Value>John</Value>
</Program-Config>
<Program-Config>
<Parameter>Device</Parameter>
<Value>TV</Value>
</Program-Config>
.
.
.
</root>
此结构还用于填充数据网格视图,如下所示:
This structure is also used to fill a datagridview like this:
Parameter | Value
__________|______
Name | John
Device | TV
这可以正常工作,我可以将所做的更改保存到xml文件中.
This is working and I can save the changes I make to a xml file.
但是我的问题是我需要读取xml文件的特定元素,但是它不能很好地工作.
However my problem is that I need to read out a specific element of the xml file and yet it is not working so good.
我的代码:
string dir;
dir = Directory.GetCurrentDirectory() + "\\config.xml";
XDocument xDoc = XDocument.Load(dir);
var xmlStr = File.ReadAllText(dir);
var str = XElement.Parse(xmlStr);
var result = str.Elements("Program-Config").
Where(x => x.Element("Parameter").Value.Equals("Device")).ToList();
for (int i = 0; i <= result.Count - 1; i++)
{
Console.WriteLine(result[i].Value);
}
但是他在Console中写的是:DeviceTV.但是我需要:电视
But what he writes in Console is: DeviceTV . But I need: TV
然后将该值用作程序的其他部分的字符串/整数.
This is then used as string / int whatever for other parts of the program.
有人可以帮我吗?
推荐答案
Value
属性返回其子节点的串联文本. result[i]
返回的元素是Parameter
元素,但是您只希望其子元素Value
.
The Value
property returns the concatenated text of its child nodes. The element returned by result[i]
is a Parameter
element, but you want its child Value
element only.
var value = (string) str.Elements("Program-Config")
.Where(x => (string) x.Element("Parameter") == "Device")
.Elements("Value")
.Single();
目前尚不清楚为什么要执行XDocument.Load
并将其丢弃.您可以通过稍微调整查询来使用该文档:
It's not clear why you're doing XDocument.Load
and throwing this away. You could use the document by tweaking your query slightly:
var value = (string) xDoc.Descendants("Program-Config")
.Where(x => (string) x.Element("Parameter") == "Device")
.Elements("Value")
.Single();
有关工作示例,请参见此小提琴.
See this fiddle for a working demo.
这篇关于读取特定的XML参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!