问题描述
我想在C#中读取xml文件并存储在C#数据结构中。
I want to read xml file in C# and store in C# data structure.
xml文件看起来像这个:
The xml file looks like this:
<?xml version =" 1.0"编码= QUOT; UTF-8英寸?>
< ElementList DocumentVersion =" 1.0.2">
< AllowedInternalElementList>
&NBSP; < SupportedRoleClassPath RoleClassPath =" ConfigurationRoleClassLib / AutomationProject">
&NBSP; &NBSP; < SupportedRoleClasses>
&NBSP; &NBSP; &NBSP; < RoleClass Path =" ConfigurationRoleClassLib / Device" />
&NBSP; &NBSP; &NBSP; < RoleClass Path =" ConfigurationRoleClassLib / Subnet" />
&NBSP; &NBSP; &NBSP; < RoleClass Path =" ConfigurationRoleClassLib / DeviceUserFolder" />
&NBSP; &NBSP; < / SupportedRoleClasses>
&NBSP; < / SupportedRoleClassPath>
< / ElementList>
<?xml version="1.0" encoding="utf-8" ?>
<ElementList DocumentVersion ="1.0.2">
<AllowedInternalElementList>
<SupportedRoleClassPath RoleClassPath="ConfigurationRoleClassLib/AutomationProject">
<SupportedRoleClasses>
<RoleClass Path= "ConfigurationRoleClassLib/Device" />
<RoleClass Path= "ConfigurationRoleClassLib/Subnet" />
<RoleClass Path= "ConfigurationRoleClassLib/DeviceUserFolder"/>
</SupportedRoleClasses>
</SupportedRoleClassPath>
</ElementList>
我尝试按以下方式执行:
I tried to do as below:
但我在'xReader.Read()'收到错误。所以请告诉我如何继续或者有更好的方法来阅读xml文件。
But I am getting error at 'xReader.Read()'. So please do let me know how can I proceed or if there is better way to read xml file.
谢谢,
Santosh
推荐答案
namespace ConsoleCS
{
using System;
using System.Xml.Linq;
using System.Xml.XPath;
public class Program
{
public static void Main(string[] args)
{
XDocument document = XDocument.Load(@"C:\Temp\test.xml");
Console.WriteLine(document.XPathSelectElement("/ElementList/AllowedInternalElementList/SupportedRoleClassPath").Attribute("RoleClassPath"));
foreach (var roleClass in document.XPathSelectElements("/ElementList/AllowedInternalElementList/SupportedRoleClassPath/SupportedRoleClasses/RoleClass"))
{
Console.WriteLine(roleClass);
}
Console.WriteLine("\nDone.");
Console.ReadLine();
}
}
}
这篇关于读取xml文件并存储在数据结构中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!