将XML中的数据提取到字典C#中



大家好!

我有以下XML文件:具有字典的键和值的XML文件我必须提取以下数据,正如你在照片上看到的那样,并将数据保存到字典中。到目前为止,我有一门课:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
[XmlRoot("Value")]
//Here is the class:
public class CodeListParser
{
public string simpleValueCode { get; set; }
public string simpleValueName { get; set; }
public CodeListParser()
{
this.simpleValueCode = simpleValueCode;
this.simpleValueName = simpleValueName;
}
public Dictionary<string, string> GetRulePlanRsa()
{
Dictionary<string, string> rulePlanRsa = new Dictionary<string, string>();
using (TextReader reader = new StreamReader(@"C:UsersmtodorovasourcereposXMLProjectXMLProjectbinDebugnet6.0C17000608_genericode.xml"))
{
XmlSerializer serializer = new XmlSerializer(typeof(CodeListParser));
//return (CodeListParser)serializer.Deserialize(reader);
}
return rulePlanRsa;
}
//The Deserialize function:
public static Dictionary<string, string> GetLegalForms()
{
Dictionary<string, string> rulePlanLegalForms = new Dictionary<string, string>();
using (TextReader reader = new StreamReader(@"C:UsersmtodorovasourcereposXMLProjectXMLProjectbinDebugnet6.0C60000022_genericode.xml"))
{
XmlSerializer serializer = new XmlSerializer(typeof(CodeListParser));
//return (CodeListParser)serializer.Deserialize(reader);
}
return rulePlanLegalForms;
}
}

在我试图提取数据的主要方法中,不幸的是没有成功:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
class Program
{
public static void Main()
{        
try
{
XmlDocument doc = new XmlDocument();
doc.Load(@"C:UsersmtodorovasourcereposXMLProjectXMLProjectbinDebugnet6.0C17000608_genericode.xml");
XmlNodeList nodes = doc.SelectNodes("//SimpleCodeList/Row/Value/SimpleValue");
List<CodeListParser> values = new List<CodeListParser>();
foreach (XmlNode xmlNode in nodes)
{
CodeListParser value = new CodeListParser();
value.simpleValueCode = xmlNode["code"].InnerText;
value.simpleValueName = xmlNode["name"].InnerText;

values.Add(value);
}
Console.WriteLine(values);
}
catch
{
throw;
}
}
}

作为输出,我正在接收,但它没有按我希望的方式工作:

System.Collections.Generic.List`1[CodeListParser]

如果你能帮我提取数据,并给我一些如何将其保存到词典中的想法,我将不胜感激。

使用Xml Linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication23
{
class Program
{
const string FILENAME = @"c:temptest.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Dictionary<string, string> rulePlanRsa = doc.Descendants("Value")
.GroupBy(x => (string)x.Attribute("ColumnRef"), y => (string)y.Element("SimpleValue"))
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}

}

最新更新