从给定节点获取兄弟姐妹

时间:2012-12-01 21:50:36

标签: c# .net xml siblings

我有这个XML文件:

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

好的,现在我有一件事:物品的价值&gt;名称节点(例如:theName2) 知道这一点我需要选择它的兄弟姐妹(val1,val2 ......)

关于如何解决这个问题的任何想法?

4 个答案:

答案 0 :(得分:4)

将xml加载到XmlDocument后,执行:

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

这是你需要的......?

答案 1 :(得分:1)

一点点XPath + Linq可能会有所帮助

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);

答案 2 :(得分:1)

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

答案 3 :(得分:0)

    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
    }

选择所有“名称”元素:

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