matt
matt

Reputation: 2352

Get a sibling from given node

I have this XML file:

 <material>
   <item>
      <name>theName1</name>
      <val1>1.1</val1>
      <val2>2.5</val2>
      <val3>5.2</val3>
   </item>
   <item>
      <name>theName2</name>
      <val1>2.1</val1>
      <val2>3.5</val2>
      <val3>6.2</val3>
   </item>
 </material>

Ok, now I have 1 thing: the value of one the the item > name nodes (for example: theName2) knowing this I need to select its siblings (val1, val2...)

Any ideas on how to go about this?

Upvotes: 2

Views: 4922

Answers (4)

Anujith
Anujith

Reputation: 9370

After Loading your xml into an XmlDocument, do:

document.SelectSingleNode("/material/item[val1='2']/name").InnerText

Is this what you need..?

Upvotes: 4

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236308

XDocument xdoc = XDocument.Load("file.xml");
IEnumerable<double> values =
    xdoc.Descendants("item")
        .Where(i => (string)i.Element("name") == "theName2") // select item
        .Select(i => i.Element("name")) // select name node 
        .SelectMany(e => e.ElementsAfterSelf()) // take siblings
        .Select(v => (double)v); // convert all value nodes to double

Upvotes: 1

L.B
L.B

Reputation: 116178

A little bit XPath + Linq may help

var xDoc = XDocument.Parse(xml); //OR XDocument.Load(filename);
string xpath = String.Format("//item[name[text()='{0}']]","theName2");

var dict = xDoc.XPathSelectElement(xpath).Descendants()
            .Where(d=>d.Name.LocalName!="name")
            .ToDictionary(x=>x.Name.LocalName,x=>(decimal)x);

Upvotes: 1

illegal-immigrant
illegal-immigrant

Reputation: 8254

    var doc = XDocument.Parse(Xml); //create XDocument from string
    var items = doc.Descendants("item"); //select all 'item' elements
    foreach (var item in items)
    {
        var childs = item.Elements().Skip(1); //skip <name> element
        foreach (var child in childs)
            Console.WriteLine(child); // val1, val2, val3, etc
    }

To select all "name" elements:

    var names = doc.Descendants("name");
    foreach (var name in names)
        Console.WriteLine(name);

Upvotes: 0

Related Questions