C#读取xml文件并为变量赋值
我试图获取项目“终端ID”和“当前配置”的值,并将它们分配给一个变量 我在互联网上找到了不同的例子,但没有人得到我想要的结果 XML文件:C#读取xml文件并为变量赋值,c#,xml,C#,Xml,我试图获取项目“终端ID”和“当前配置”的值,并将它们分配给一个变量 我在互联网上找到了不同的例子,但没有人得到我想要的结果 XML文件: <TerminalOverview xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Bmt.BmtSharp.WebInterface.Backend.API.App.Home.Model">
<TerminalOverview xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Bmt.BmtSharp.WebInterface.Backend.API.App.Home.Model">
<InfoItems>
<InfoItem>
<Name>Device name</Name>
<Value/>
</InfoItem>
<InfoItem>
<Name>Terminal ID</Name>
<Value>253896528</Value>
</InfoItem>
<InfoItem>
<Name>Current Configuration</Name>
<Value>BmtVersion - 1.1.32</Value>
</InfoItem>
<InfoItem>
<Name>Local Time</Name>
<Value>15/10/2017 13:58:14</Value>
</InfoItem>
<InfoItem>
<Name>Time zone</Name>
<Value>Amsterdam</Value>
</InfoItem>
</InfoItems>
<Message xmlns="http://schemas.datacontract.org/2004/07/Bmt.BmtSharp.WebInterface.Backend.API.Common.Models" i:nil="true"/>
<Success xmlns="http://schemas.datacontract.org/2004/07/Bmt.BmtSharp.WebInterface.Backend.API.Common.Models">true</Success>
</TerminalOverview>
设备名
终端ID
253896528
当前配置
BmtVersion-1.1.32
当地时间
15/10/2017 13:58:14
时区
阿姆斯特丹
真的
我希望将“终端ID”的值分配给变量terminalID,“当前配置”的值分配给变量softwareVersion
如何实现这一点?下面的代码将把所有项目放入字典中。然后可以从字典中获取id和配置
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILEMNAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILEMNAME);
XElement root = doc.Root;
XNamespace ns = root.GetDefaultNamespace();
Dictionary<string, string> dict = root.Descendants(ns + "InfoItem")
.GroupBy(x => (string)x.Element(ns + "Name"), y => (string)y.Element(ns + "Value"))
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Xml;
使用System.Xml.Linq;
命名空间控制台应用程序1
{
班级计划
{
常量字符串FILEMNAME=@“c:\temp\test.xml”;
静态void Main(字符串[]参数)
{
XDocument doc=XDocument.Load(FILEMNAME);
XElement根=文档根;
XNamespace ns=root.GetDefaultNamespace();
Dictionary dict=root.substands(ns+“InfoItem”)
.GroupBy(x=>(字符串)x.Element(ns+“名称”),y=>(字符串)y.Element(ns+“值”))
.ToDictionary(x=>x.Key,y=>y.FirstOrDefault());
}
}
}
可能重复您的意思您发现了许多示例,但没有一个是您想要的?您能否显示读取xml节点的代码?