如何在wpf中使用Linq到xml概念从xml元素获取值

时间:2012-06-27 06:51:24

标签: c# wpf linq-to-xml

XElement MyFamily = new XElement("MyFamily",
                                new XElement("Parents",
                                    new XElement("Father", "Anjappan",
                                        new XAttribute("Id", "AA1234")),
                                    new XElement("Mother", "Thaiyamuthu",
                                        new XAttribute("Id", "AA4567"))),
                                new XElement("Brothers", "Senthil,Saravanan,Sathish"),
                                new XElement("Systers", "Povunamma,Pazhaniyamma,Sangeetha"));
        MyFamily.Save(@System.AppDomain.CurrentDomain.BaseDirectory + "MyFamily_RemoveElement.xml");

在这里,我希望使用Linq to xml概念获得值(“Anjappan”)和 Id 值(“AA12345”)。我应该怎么做。

2 个答案:

答案 0 :(得分:1)

试试这个,

 var element = MyFamily.Descendants("Father")
                  .Where(
                   p => p.Value == "Anjappan" 
                   && p.Attribute("Id").Value == "AA1234"
                   ).FirstOrDefault();

答案 1 :(得分:0)

使用Descendants获取节点,Attributes获取属性,使用Value获取元素/节点值。

    var fatherNode  = MyFamily.Descendants("Father"); //Father Nodes
    var fatherId = fatherNode.Attributes("Id").First().Value; // "AA1234")
    var farthName = fatherNode.First().Value; //"Anjappan"