Home > other >  Extracting Key value from XML tags C# LINQ
Extracting Key value from XML tags C# LINQ

Time:09-16

void Main()
{
    string xml = @"<root>                 
<Page1>
<Key_Head>Name1</Key_Head>
<Key_Title>value1</Key_Title>
</Page1>
<Page1>
<Key_Head>Name2</Key_Head>
<Key_Title>value2</Key_Title>
</Page1>
</root>";
    var doc1 = XDocument.Parse(xml);
    var result = ConvertXmlToDic(doc1.Root);
}

private static List<NameValuePair> ConvertXmlToDic(XElement element)
{
    var result =
        element
            .Elements()
            .Select(e => new
            {
                Name = e.Name.ToString(),
                Value = (e.Descendants().Count() == 0)
                ? e.Value
                : ConvertXmlToDic(e).ToString()
            })
            .ToDictionary(e => e.Name, e => e.Value)
            .Select(e => new List<NameValuePair>()
            {
                new NameValuePair() { Name = e.Key, Value = e.Value }
            });
    return (List<NameValuePair>)result;
}

How do I get the tag values for <Key_Head>Name1</Key_Head><Key_Title>value1</Key_Title> as key values. Like list of (Name1,Value1) ? This is what I have tried so far.

CodePudding user response:

You can simplify the logic to retrieve Key_Head and Key_Title as below:

private static List<NameValuePair> ConvertXmlToDic(XElement element)
{
    var result = element.Elements()
        .Select(e => new NameValuePair
                {
                    Name = e.Element("Key_Head").Value, 
                    Value = e.Element("Key_Title").Value
                })
        .ToList();
    return result;
}

Output

Name: Name1, Value: value1

Name: name2, Value: value2

Sample program

  • Related