简体   繁体   中英

How do I get the values of all the nodes within the first and last child nodes of an element in C#

I have an XML node with the following structure:

<package>package <name>com</name>.<name>sample</name>.<name>app1</name>;</package>

The name tag can appear a random number of times, and what I want is to get the values of all the child nodes between the first and last child in the list of elements, to get a value like this: com.sample.app1 .

I guess I can apply some type of regular expression to the value of the package node which always starts with "package " and ends with ";". Or maybe some LINQ or lambda expression?

What would be the most efficient way of doing it since I'm processing a large XML file and this node is part of it?

Well in this case I'd just use:

var package = string.Join(".", element.Elements("name").Select(x => x.Value));

(Where element is the XElement representing <package> .)

Or if there's a different namespace:

XNamespace ns = "http://some.namespace/here";
var package = string.Join(".", element.Elements(ns + "name")
                                      .Select(x => x.Value));

(Where element is the XElement representing <package> and ns + "name" combines a string with an XNamespace to give the right XName .)

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