带有属性(“id”)的where子句的LINQ to XML查询.value ==“1”

时间:2011-04-27 12:24:40

标签: linq-to-xml

我想将一个元素添加到XML文件中,条件为:

like where attribute("id").value=="1"

在此代码中,where子句不起作用:

string xmlFilePath = MapPath("Employees.xml");
XDocument xmlDoc = XDocument.Load(xmlFilePath);
try
{
    xmlDoc.Element("employees").Element("employee")
        .Where(employee => employee.Attribute("id").Value == "2").FirstOrDefault())
        .Add(new XElement("city", "welcome"));

    xmlDoc.Save(xmlFilePath);
}
catch (XmlException ex)
{
    //throw new XmlException
}

1 个答案:

答案 0 :(得分:0)

这可能会更好:

XDocument xmlDoc = XDocument.Load(xmlFilePath);
try
{
    xmlDoc
        // get the employees element
        .Element("employees")
        // get all the employee elements
        .Elements("employee")
        // but filter down to the first one that has id == 2
        .Where(employee => employee.Attribute("id").Value == "2").FirstOrDefault()
        // and add a new city element to it
        .Add(new XElement("city", "welcome"));
    // save the document
    xmlDoc.Save("D:\\x.xml");
}
catch (XmlException ex)
{
    //throw new XmlException
}