【发布时间】:2015-12-01 18:00:47
【问题描述】:
我正在学习 XML 查询和 Xdocument,但在更新现有元素的属性时遇到了问题。这是我的 WCF 服务。第二部分有效(使用属性创建新元素。问题是我的查询不能返回任何结果,并且代码总是添加一个新元素。
//this will insert the officer location and status into the xml data file
//I read about how to do this at http://prathapk.net/creating-wcf-service-to-store-read-data-in-xml-database/
//and https://msdn.microsoft.com/en-us/library/bb387041.aspx
public void InsertOfficerData(string OfficerID, double latitude, double longitude, int StatusCode)
{
//open xml file
XDocument doc = XDocument.Load(HttpContext.Current.Server.MapPath("Officers.xml"));
//linq query to find the element with the officer ID if it exists
IEnumerable<XElement> officer =
from el in doc.Element("Officers").Elements("Officer")
where (string)el.Attribute("OfficerID") == OfficerID
select el;
bool updated = false;
//update officer attributes
foreach (XElement el in officer)
{
//update attributes
el.Attribute("Latitude").Value = Convert.ToString(latitude);
updated = true;
doc.Save(HttpContext.Current.Server.MapPath("Officers.xml"));
}
//if an officer with the id was not found
if (!updated)
{
//add the element with attributes
doc.Element("Officers").Add(new XElement("Officer",
new XAttribute("ID", OfficerID),
new XAttribute("Latitude", latitude),
new XAttribute("Longitude", longitude),
new XAttribute("Status", StatusCode)));
doc.Save(HttpContext.Current.Server.MapPath("Officers.xml"));
}
}
我的 XML 文件结构示例:
<?xml version="1.0" encoding="utf-8"?>
<Officers>
<Officer ID="Dust" Latitude="4" Longitude="5" Status="3" />
</Officers>
【问题讨论】: