草庐IT

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

coder 2024-07-01 原文

我正在学习 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/

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

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  3. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  4. ruby - 多个属性的 update_column 方法 - 2

    我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2

  5. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  6. ruby - Nokogiri 剥离所有属性 - 2

    我有这个html标记:我想得到这个:我如何使用Nokogiri做到这一点? 最佳答案 require'nokogiri'doc=Nokogiri::HTML('')您可以通过xpath删除所有属性:doc.xpath('//@*').remove或者,如果您需要做一些更复杂的事情,有时使用以下方法遍历所有元素会更容易:doc.traversedo|node|node.keys.eachdo|attribute|node.deleteattributeendend 关于ruby-Nokog

  7. ruby-on-rails - Rails 模型——非持久类成员或属性? - 2

    对于Rails模型,是否可以/建议让一个类的成员不持久保存到数据库中?我想将用户最后选择的类型存储在session变量中。由于我无法从我的模型中设置session变量,我想将值存储在一个“虚拟”类成员中,该成员只是将值传递回Controller。你能有这样的类(class)成员吗? 最佳答案 将非持久属性添加到Rails模型就像任何其他Ruby类一样:classUser扩展解释:在Ruby中,所有实例变量都是私有(private)的,不需要在赋值前定义。attr_accessor创建一个setter和getter方法:classUs

  8. ruby - 当使用::指定模块时,为什么 Ruby 不在更高范围内查找类? - 2

    我刚刚被困在这个问题上一段时间了。以这个基地为例:moduleTopclassTestendmoduleFooendend稍后,我可以通过这样做在Foo中定义扩展Test的类:moduleTopmoduleFooclassSomeTest但是,如果我尝试通过使用::指定模块来最小化缩进:moduleTop::FooclassFailure这失败了:NameError:uninitializedconstantTop::Foo::Test这是一个错误,还是仅仅是Ruby解析变量名的方式的逻辑结果? 最佳答案 Isthisabug,or

  9. ruby - 有人可以帮助解释类创建的 post_initialize 回调吗 (Sandi Metz) - 2

    我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法

  10. ruby - 查找字符串中的内容类型(数字、日期、时间、字符串等) - 2

    我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s

随机推荐