-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.

Jonathan
  • 13,947
  • 17
  • 94
  • 123
  • What form do you have the array in at the moment? Already parsed, or as text? In a document, or not? – Jon Skeet Apr 05 '12 at 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 Apr 05 '12 at 16:31
  • -1 This question is not specific enough to formulate a proper answer. Good luck with this. – Chuck Savage Apr 05 '12 at 17:14
  • @ChuckSavage I created a new answer like you suggested due to his changing requirements. – Chris Benard Apr 05 '12 at 17:41

2 Answers2

3

Like this, perhaps?

XmlNode[] nodes = ...;
string value = nodes.Single(n => n.LocalName == "Node2").InnerXml;
// or .InnerText, depending on what you need.
Michael Liu
  • 52,147
  • 13
  • 117
  • 150
  • 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 Apr 05 '12 at 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();
Chris Benard
  • 3,167
  • 2
  • 29
  • 35