Searching an array of XML Nodes

Go To StackoverFlow.com

-2

I have an array of System.Xml.XmlNode with data similar to this:

[0] = <Node1 xmlns="---">N1Data</Node1>

[1] = <Node2 xmlns="---">N2Data</Node2>

[2] = <Node3 xmlns="---">N3Data</Node3>

Using LINQ, how could I select the inner data of Node2? This seems trivial with an XDocument, but my data format is nonnegotiable as it's supplied by an external resource.

Thanks in advance.

2012-04-05 16:24
by Jonathan
What form do you have the array in at the moment? Already parsed, or as text? In a document, or not - Jon Skeet 2012-04-05 16:28
@JonSkeet The array consists of XML Nodes with parsed data, with the OuterXml of each looking similar to the 3 examples I've presented. As far as I'm aware these do not constitute documents - Jonathan 2012-04-05 16:31
-1 This question is not specific enough to formulate a proper answer. Good luck with this - Chuck Savage 2012-04-05 17:14
@ChuckSavage I created a new answer like you suggested due to his changing requirements - Chris Benard 2012-04-05 17:41


3

Like this, perhaps?

XmlNode[] nodes = ...;
string value = nodes.Single(n => n.LocalName == "Node2").InnerXml;
// or .InnerText, depending on what you need.
2012-04-05 16:43
by Michael Liu
Thank you. This was exactly what I was looking for and whilst I could've achieved the same with XDocument, it seemed a little inefficient to parse all the XML into a new object - Jonathan 2012-04-05 21:25


1

New Answer: Completely changed to not use XDocument at all, per author's request:

string[] elementArray = new[]
{
    "<Node1 xmlns=\"foo\">Bar</Node1>",
    "<Node2 xmlns=\"foo\">Bar</Node2>",
    "<Node3 xmlns=\"foo\">Bar</Node3>"
};

var search = "Node2";
string result = elementArray
    .Where(x => x.Split(' ').First().Substring(1) == search)
    .Select(x =>
    {
        int closeBrace = x.IndexOf(">");
        int openBrace = x.IndexOf("<", closeBrace);
        return x.Substring(closeBrace + 1, openBrace - closeBrace - 1);
    })
    .Single();
2012-04-05 17:08
by Chris Benard
Ads