简体   繁体   中英

Visual Studio c# / xml get specific sub-elements

Can someone help me with the best way to get specific sub-element values from an XML file using visual studio (c#). I am new to using XML never mind using it in visual studio.

Here is some example XML, I want to get "data_A" and "data_B" from level 1 only, for example, but at the same time, I would like to be able to reuse the code to do the same for level 2, without the need to rewrite everything.

<game name="test">
    <area level="1">
        <data_a> foo </data_a>
        <data_b> foo </data_b>
        <data_c> foo </data_c>
    </area>
    <area level="2">
        <data_a> foo </data_a>
        <data_b> foo </data_b>
        <data_c> foo </data_c>
    </area>
</game>

Also, sorry for the wall of spam.

Best is relative as famous mathematician Lewis Carroll said. Try this xml linq solution:

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);

            var resuts = doc.Descendants("area").Where(x => (int)x.Attribute("level") == 1).Elements().Select(x => new {
                name = x.Name.LocalName,
                value = (string)x
            }).ToList();

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM