草庐IT

c# - 在 C# 中实时编辑 xml。删除包含特定值的节点

coder 2024-07-05 原文

我有一个这样类型的 xml 文档:

<?xml version="1.0" encoding="UTF-16"?>
<Recordset>
  <Table>Recordset</Table>
  <Rows>
    <Row>
      <Fields>
        ...
        <Field>
          <Alias>StatusName</Alias>
          <Value>Scheduled</Value>
        </Field>
        <Field>
          <Alias>U_Revision</Alias>
          <Value>code00</Value>
        </Field>
        <Field>
          <Alias>U_Quantity</Alias>
          <Value>10.000000</Value>
        </Field>
        <Field>
          <Alias>U_ActualQty</Alias>
          <Value>0.000000</Value>
        </Field>
        ...
      </Fields>
    </Row>
    ...
    <Row>
      <Fields>
        ...
        <Field>
          <Alias>StatusName</Alias>
          <Value>Scheduled</Value>
        </Field>
        <Field>
          <Alias>U_Revision</Alias>
          <Value>code00</Value>
        </Field>
        <Field>
          <Alias>U_Quantity</Alias>
          <Value>150.000000</Value>
        </Field>
        <Field>
          <Alias>U_ActualQty</Alias>
          <Value>0.000000</Value>
        </Field>
        ...
      </Fields>
    </Row>
  </Rows>
</Recordset>

我在别名为 StatusName 的字段中有不同的值。有一些 Scheduled、notScheduled、Realeased、Finished 等值。我想做的是删除包含别名 StatusName 和值的节点的每个节点,比如 Scheduled 或 Finished。

我想或多或少地以那种方式来做这件事,但是我做错了什么。有人可以让我走正确的路吗?

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xml);
            XmlNodeList nodes = xmlDocument.SelectNodes("//Rows[@StatusName='Finished']");
            for (int i = nodes.Count - 1; i >= 0; i--)
            {
                nodes[i].ParentNode.RemoveChild(nodes[i]);
            }
            var newXml = nodes.ToString();

如果包含别名 StatusName 并且特定值可以说是 Finished,我想删除整个节点。

我希望在新的字符串变量中得到结果。

最佳答案

我喜欢使用带有 xml 的 DataTable,我发现它非常容易。 我使用 DataTable 来处理您的节点。 所以,我拿了你的 xml 文件并为你写了一些可能对你有帮助的代码:

//READ THE XML FILE
XmlDocument xmlDoc = new XmlDocument();
//My path
xmlDoc.LoadXml(Properties.Resources.test);

//Read the xml file into a dataSet
DataSet ds = new DataSet();
XmlNodeReader xnr = new XmlNodeReader(xmlDoc);
ds.ReadXml(xnr);

//Your data will be store in the 4's dataTable of the dataSet ( the <field> )
for(int i=0;i<ds.Tables[4].Rows.Count;i++)
{
    //Check the value as you wish
    //Here i want to suppress all the <Field> nodes with <Value> = "Scheduled"
    if ( ds.Tables[4].Rows[i]["Value"].ToString().Equals("Scheduled"))
    {
        //RemoteAt will remove all the node, so the node <Field> in your example data
        ds.Tables[4].Rows.RemoveAt(i);
        //If you want to only remove the node <Value>  (and not all the <Field> node ) just do ds.Tables[4].Rows["Value"]=null;
     }
}
//Write your new content in a new xml file

//As you wanted here you just read the new xml file created as a string
using (var stringWriter = new StringWriter())
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
    ds.WriteXml(xmlTextWriter);
    xmlTextWriter.Flush();
    stringWriter.GetStringBuilder().ToString();
    //Here the result is in stringWriter,  and  there is 6 <Field> nodes, and not 8 like before the suppress
}

//If you want to create a new xml file with the new content just do 
ds.WriteXml(yourPathOfXmlFile);
//( like rewriting the previous xml file )

关于c# - 在 C# 中实时编辑 xml。删除包含特定值的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38261881/

有关c# - 在 C# 中实时编辑 xml。删除包含特定值的节点的更多相关文章

  1. ruby - 在 Ruby 中实现 `call_user_func_array` - 2

    我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)

  2. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  3. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  4. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  5. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  6. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  7. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

  8. ruby-on-rails - 如何在 Ruby on Rails 中实现无向图? - 2

    我需要在RubyonRails中实现无向图G=(V,E)并考虑构建一个Vertex和一个Edge模型,其中Vertex有_多条边。由于边恰好连接两个顶点,您将如何在Rails中执行此操作?您是否知道任何有助于实现此类图表的gem或库(对重新发明轮子不感兴趣;-))? 最佳答案 不知道有任何现有库在ActiveRecord之上提供图形逻辑。您可能必须实现自己的Vertex、EdgeActiveRecord支持的模型(请参阅Rails安装的rails/activerecord中的vertex.rb和edge.rb/test/fixtur

  9. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  10. C# 到 Ruby sha1 base64 编码 - 2

    我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha

随机推荐