0
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”)。我该怎么做。

4

2 回答 2

1

尝试这个,

 var element = MyFamily.Descendants("Father")
                  .Where(
                   p => p.Value == "Anjappan" 
                   && p.Attribute("Id").Value == "AA1234"
                   ).FirstOrDefault();
于 2012-06-27T06:59:32.220 回答
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"
于 2012-06-27T06:59:19.000 回答