[英]Get Each Value on an XML Node
I have an XML that looks like this:我有一个看起来像这样的 XML:
<HiddenTopicsValues TopicCodes="TopicValues">
<Topic>
<Code>topic_aboutme</Code>
<Value>1</Value>
</Topic>
<Topic>
<Code>topic_aboutyou</Code>
<Value>1</Value>
</HiddenTopicsValues>
My goal is to create a Dictionary that lets the <Code>
act as the Key, and <Value>
as the Value (of the Dictionary).我的目标是创建一个字典,让
<Code>
作为键, <Value>
作为(字典的)值。 I declared the dictionary as shown below:我声明了字典,如下所示:
Dictionary<string,int> dictionary_topics = new Dictionary<string,int>();
And used a for loop to iterate all the values in the XML:并使用 for 循环迭代 XML 中的所有值:
// Load XML Document
XmlDocument xmlTopics = new XmlDocument();
xmlTopics.Load(path);
// Get All Hidden Topics
XmlNodeList ndTopics = xmlTopics.GetElementsByTagName("Topic");
for (int i = 0; i < ndTopics.Count; i++)
{
string _topicCode = ndTopics[i].InnerText[0].ToString();
int _topicValue = ndTopics[i].InnerText[1].ToString();
// Add Topic to Dictionary
dictionary_topics.Add(_topicCode, _topicValue);
}
I thought that this: ndTopics[i].InnerText[0]
would return this: topic_aboutme
我认为这个:
ndTopics[i].InnerText[0]
会返回这个: topic_aboutme
And this: ndTopics[0].InnerText[1]
would return this: 1
这:
ndTopics[0].InnerText[1]
将返回: 1
Based on the given XML.基于给定的 XML。
I tried displaying ndTopics[0].InnerText
and it shows this:我尝试显示
ndTopics[0].InnerText
并显示:
topic_aboutme1
How can I separate the topic_aboutme(<Code>)
and 1(<Value>)
?如何分开
topic_aboutme(<Code>)
和1(<Value>)
?
Forgive my naiveness, I'm not really used in utilising XML.原谅我的幼稚,我并没有真正习惯使用 XML。
Real easy in Xml Linq:在 Xml Linq 中非常容易:
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 FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Dictionary<string, string> dict = doc.Descendants("Topic")
.GroupBy(x => (string)x.Element("Code"), y => (string)y.Element("Value"))
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.