我想将一个元素添加到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
}
答案 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
}