Question

I have an XML like this

<Node Name="segment_@85D819AE">
    <Node Name="segment_body37sub0">
        <Node Name="face_82C1EB14_4"/>
    </Node>
    <Node Name="segment_body37sub1">
        <Node Name="face_82C1ED90_5"/>
    </Node>
    <Node Name="segment_body37sub2">
        <Node Name="face_82C1EF38_6"/>
    </Node>
</Node>

I want to get on the following from the above XML.

face_82C1EB14_4
face_82C1ED90_5
face_82C1EF38_6

Basically all the Last elements in to a List

I am using c# Frame work 4.0.

Était-ce utile?

La solution

It sounds like you're just trying to find the names of all elements with no child elements, then project from each of those elements to the Name attribute value:

var names = doc.Descendants() // Or Descendants("Node")
               .Where(x => !x.Elements().Any())
               .Select(x => x.Attribute("Name").Value);

Autres conseils

I made this before reading the updates and seeing you got an answer. Leaving it here just in case.

    internal class Program
    {
        private static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("C:/xmlExample.xml");

            XmlNode firstChild = doc.DocumentElement.FirstChild;
            List<string> returningStrList = new List<string>();
            GetStringList(doc.DocumentElement.ParentNode, returningStrList);

            Console.WriteLine();
        }

        private static void GetStringList(XmlNode node, List<string> strList)
        {
            if (node.HasChildNodes)
                foreach (XmlNode childNode in node.ChildNodes)
                    GetStringList(childNode, strList);

            if (!string.IsNullOrEmpty(node.Value))
                strList.AddRange(node.Value.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
        }
    }


XML structure:
<?xml version='1.0'?>
<example xmlns="urn:example-schema">
    <myNode>
        <data a="1000" b="20">
            100 20000
        </data>
        <data a="12512" b="25">
            200 1000
        </data>

        <data>
           <subData k="aaaa">
               subDataText 20
           </subData>
           400 kakaaka
        </data>
    </myNode>
</example>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top