简体   繁体   中英

LINQ to XML (Dynamic XML)

I have an XML file which has kind of a similar structure that you can see below: I would like to select title and subitems using LINQ to XML . The difficulties that I have: sometimes a subitem can be just one and sometimes it can be 20 subitems, and I need to add them to List<string>.

<?xml version="1.0"?>
<items>
    <item>
        <title>Name of the title</title>
        <subitem>Test</subitem>
        <subitem1>Test</subitem1>
        <subitem2>Test</subitem2>
        <subitem3>Test</subitem3>
        <subitem4>Test</subitem4>
        <subitem5>Test</subitem5>
    </item>
    <item>
        <title>Name of the title</title>
        <subitem>Test</subitem>
        <subitem1>Test</subitem1>
        <subitem2>Test</subitem2>
        <subitem3>Test</subitem3>
    </item>
    <item>
        <title>Name of the title</title>
        <subitem>Test</subitem>
        <subitem1>Test</subitem1>
    </item>
</items>
XDocument xdoc = XDocument.Load(path_to_xml);
var query = from i in xdoc.Descendants("item")
            select new
            {
                Title = (string)i.Element("title"),
                Subitems = i.Elements()
                            .Where(e => e.Name.LocalName.StartsWith("subitem"))
                            .Select(e => (string)e)
                            .ToList()
            };

The solution, including getting the titles, is:

XDocument yourXDocument = XDocument.Load(yourXmlFilePath);
IEnumerable<Tuple<XElement, IEnumerable<XElement>>> yourSubItems =
    yourXDocument.Root.Descendants()
                 .Where(xelem => xelem.Name == "title")
                 .Select(xelem => new Tuple<XElement, IEnumerable<XElement>>(xelem, xelem.Parent.Elements().Where(subelem => subelem.Name.LocalName.StartsWith("subitem")));

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