.NET将标记转换为地图

时间:2016-06-01 13:00:05

标签: c# .net xml dictionary

我需要将包含标签的文本转换为简单的地图(字典)。文字如下:

<tag1>text1</tag1><tag2>text2></tag2> 

我需要的是这样的事情:

Dictionary<string,string> dicTags = new Dictionary<string,string>();
dicTags["tag1"] = "text1";
dicTags["tag2"] = "text2";

如果我们事先不知道标签名称,这是一种简单的方法吗?

2 个答案:

答案 0 :(得分:2)

假设发布的XML片段包含在单个根元素中,以便它生成格式良好的XML,您可以按照以下步骤生成所需的字典:

<span>

<强> dotnetfiddle demo

输出

var raw = @"<root><tag1>text1</tag1><tag2>text2</tag2> </root>";
var doc = XDocument.Parse(raw);
var dicTags = doc.Root.Elements().ToDictionary(e => e.Name.LocalName, e => (string)e);
foreach(var kv in dicTags)
{
    Console.WriteLine("Key: {0}, Value: {1}", kv.Key, kv.Value);
}

答案 1 :(得分:1)

试试这个

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


namespace ConsoleApplication96
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = "<root><tag1>text1</tag1><tag2>text2></tag2></root>";
            XElement root = XElement.Parse(xml);
            Dictionary<string, string> dict1 = new Dictionary<string, string>();

            //if each tag is unique
            dict1 = root.Elements().GroupBy(x => x.Name.LocalName, y => y).ToDictionary(x => x.Key, y => y.FirstOrDefault().Value);
            //if tag names are duplicated then use this
            Dictionary<string, List<string>> dict2 = new Dictionary<string, List<string>>();
            dict2 = root.Elements().GroupBy(x => x.Name.LocalName, y => y).ToDictionary(x => x.Key, y => y.Select(z => z.Value).ToList());
         }
    }
}