如何在C#中使用XmlDocument和XmlNode修改现有XML文件 [英] How to modify existing XML file with XmlDocument and XmlNode in C#

查看:367
本文介绍了如何在C#中使用XmlDocument和XmlNode修改现有XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在应用程序初始化时,我已经实现了使用 XmlTextWriter 在下面创建XML文件的功能。

I already implemented to create the XML file below with XmlTextWriter when application initialization.

并且我不知道如何使用 XmlDocument & XmlNode

And know I don't know how to update the childNode id value with XmlDocument & XmlNode.

是否有一些属性可以更新id值?我尝试了 InnerText ,但失败了。

Is there some property to update the id value? I tried InnerText but failed. thank you.

<?xml version="1.0" encoding="UTF-8"?>
<Equipment xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <License licenseId="" licensePath=""/>
  <DataCollections>
    <GroupAIDs>
      <AID id="100">
        <Variable id="200"/>
        <Variable id="201"/>
      </AID>
      <AID id="">
        <Variable id="205"/>
      </AID>
      <AID id="102"/>
    </GroupAIDs>
    <GroupBIDs>
      <BID id="2000">
        <AID id="100"/>
      </BID>
      <BID id="2001">
        <AID id="101"/>
        <AID id="102"/>
      </BID>
    </GroupBIDs>
    <GroupCIDs>
      <BID id="8"/>
      <BID id="9"/>
      <BID id="10"/>
    </GroupCIDs>
  </DataCollections>
</Equipment>


推荐答案

您需要执行以下操作:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

这篇关于如何在C#中使用XmlDocument和XmlNode修改现有XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆