c# - 寻求有关在 XML XDocument 中查找元素和更新属性的帮助

标签 c# .net xml linq

我正在学习 XML 查询和 Xdocuments,但在更新现有元素的属性时遇到了问题。这是我的 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>

最佳答案

您正在检查名为 OfficerID 的属性, 但您只创建了一个名为 ID 的属性与新 OfficerID变量。

要么改变

where (string)el.Attribute("OfficerID") == OfficerID

成为

where (string)el.Attribute("ID") == OfficerID

改变

new XAttribute("ID", OfficerID),

成为

new XAttribute("OfficerID", OfficerID),

另一件可能很关键的事情是,即使您找到了警官,搜查也不会在您成功之前进行。枚举会延迟执行,直到必须这样做。因此,对于您的 foreach,将其更改为:

foreach (XElement el in officer.ToList())

ToList()执行可枚举的,其他人也是如此 ToArray()等等。它也是一个安全网,以防您删除元素。

旁注,与问题分开:

既然你调用doc.Save()在 foreach 和 new officer 分支中,将保存作为最后发生的事情放在方法的底部。

关于c# - 寻求有关在 XML XDocument 中查找元素和更新属性的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34027006/

相关文章:

java - 如何在Hibernate框架中正确生成xml

c# - 构造 linq 查询

c# - 在将表单发送到后端之前,如何将密码字符串转换为 Base64 字符串?

c# - 如何检测 Windows 10 周年更新?

c# - ASP.NET 身份 2.0 : How to rehash password

xml - XPath 和 Jenkins Plot 插件

c# - 使用 Lucene.NET 和 C# 对 blob 内的数据建立索引

c# - 集合和列表

.net - 来自不同客户端的调用之间未清除 WCF AuthorizationContext。 (原为 : When does a WCF service session actually end? )

java - DOM 中的文件加载是如何工作的?